阿里今晚笔试题目

两道算法题,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;
}


#阿里面试##阿里巴巴##笔试题目#
全部评论
第一题我也是楼主这个思路 但是没去快速幂 一个都没过
1 回复 分享
发布于 2020-03-23 20:17
第一题不用快速幂就过不了么
点赞 回复 分享
发布于 2020-03-23 20:12
 我第二题BFS一个错误的解法过了40%, 自己觉得对的解法却只过了10%= =
点赞 回复 分享
发布于 2020-03-23 20:16

相关推荐

头像
2024-12-19 18:11
英特尔_Software_engineer
下水道鼠鼠鼠鼠:男的能去当技师吗 好进吗
点赞 评论 收藏
分享
评论
10
19
分享

创作者周榜

更多
牛客网
牛客企业服务