阿里今晚笔试题目
两道算法题,1小时
第一道数学题
C(1,n)*1 + C(2,n)*2 + ... + C(n,n)*n推出n*2^(n-1)
然后快速幂取模,AC
#include <iostream> #include <algorithm> #include <vector> #include <cmath> using namespace std; const int mod = 1e9+7; typedef long long ll; ll mod_pow(ll x, ll n){ ll ans = 1; while(n > 0){ if(n&1) ans = ans * x % mod; x = x * x % mod; n >>= 1; } return ans; } int main(){ int n; cin >> n; ll temp = mod_pow(2, n-1); cout << ((n % mod) * (temp % mod)) % mod; return 0; }
第二道图论
没时间写了,BFS瞎搞一发80%过
#include <iostream> #include <algorithm> #include <vector> #include <cmath> #include <queue> using namespace std; const int MAXN = 1E3; int vis[MAXN][MAXN]; char Map[MAXN][MAXN]; int step[MAXN][MAXN]; int n, m; struct node{ int x, y; }in, out, beg; bool check(int x, int y){ if(!vis[x][y] && x >= 1 && y >= 1 && x <= n && y <= m && Map[x][y] != '#') return true; return false; } int dir[4][2] ={ {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; int num = 5; int bfs(){ vis[beg.x][beg.y] = 1; step[beg.x][beg.y] = 0; queue<node> q; q.push(beg); while(!q.empty()){ out = q.front(); q.pop(); for(int i = 0; i < 5; i++){ if(i != 4){ in.x = out.x + dir[i][0]; in.y = out.y + dir[i][1]; }else{ in.x = n+1-out.x; in.y = m+1-out.y; num--; if(num < 0){ continue; } } if(check(in.x, in.y)){ if(Map[in.x][in.y] == 'E') return step[out.x][out.y] + 1; q.push(in); vis[in.x][in.y] = 1; step[in.x][in.y] = step[out.x][out.y] + 1; } } } return -1; } int main(){ cin >> n >> m; for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ cin >> Map[i][j]; if(Map[i][j] == 'S'){ beg.x = i; beg.y = j; } } } cout << bfs(); return 0; }