阿里春招笔试2020.3.23(快速幂/BFS)

申明:大概题意是从牛客网讨论区嫖的,题目的输入、输出以及数据数据范围也有些不知,大家看看思路就好,这些细节就不管了QAQ。有错欢迎纠正~
阿里笔试3.23

题目一(快速幂)

从n个人中选择任意数量的人员组成一支队伍,然后从一支队伍中选出一位队长,不同的队长算不同的组合,问这样的组合的数量对10^9+7取模 。
数据范围:1 <= n <= 1000000000;
思路:答案为 n 2 n 1 n*2^{n-1} ,选择一个做领导,另外的人都有2种选择。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int mod = 1e9+7;

int quickp(ll a,ll p) {
	ll res = 1;
	while(p) {
		if(p&1) res = res*a%mod;
		a = a*a%mod;
		p >>= 1;
	}
	return res;
}
int main() {
	ll n;
	scanf("%lld",&n);
	printf("%lld\n",n*quickp(2LL,n-1)%mod);
} 

题目二(BFS)

一个地图n*m,包含1个起点,1个终点,其他点包括可达点和不可达点。 每一次可以:上下左右移动,或使用1点能量从(i,j)瞬间移动到(n-1-i, m-1-j),最多可以使用5点能量。
数据范围:2 <= n,m <= 500;

输入:
4 4
#S..
E#..
....
....
输出:
4
解释:S(0,1)先瞬移到(3, 2),然后往上一步,往右一步,瞬移到E,一共4

思路:BFS

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 510;

int n,m;
char s[maxn][maxn];
bool vis[maxn][maxn];
struct node{
	int x,y,step;
	int count;
}cur,tmp;
bool check(int x,int y) {
	if(x<0 || x>=n || y<0 || y>= m) return 0;
	if(s[x][y] == '#') return 0;
	return 1;
}
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
int bfs(int sx,int sy) {
	cur.x = sx;cur.y = sy;
	cur.step = 0;cur.count = 5;
	queue<node> q;
	int x,y;
	vis[sx][sy] = 1;
	q.push(cur);
	while(!q.empty()) {
		cur = q.front();
		q.pop();
		if(s[cur.x][cur.y] == 'E') return cur.step;
		for(int i = 0;i < 4;++i) {
			x = cur.x+dx[i];
			y = cur.y+dy[i];
			if(!check(x,y) || vis[x][y]) continue;
			tmp = cur;
			tmp.x = x;tmp.y = y;
			tmp.step++;
			q.push(tmp);
		}
		x = n-1-cur.x;
		y = m-1-cur.y;
		if(!check(x,y) || vis[x][y]) continue;
		cur.x = x;cur.y = y;
		cur.step++;cur.count--;
		q.push(cur);
	}
	return -1;
}
int main() {
	scanf("%d%d",&n,&m);
	int x,y;
	for(int i = 0;i < n;++i) {
		scanf("%s",s[i]);
		for(int j = 0;j < m;++j) {
			if(s[i][j] == 'S') {
				x = i;y =j;
				break;
			}
		}
	}
	printf("%d\n",bfs(x,y));
}
/*
4 4
#S..
E#..
....
....

4

*/
发布了152 篇原创文章 · 获赞 2 · 访问量 6444

猜你喜欢

转载自blog.csdn.net/weixin_43918473/article/details/105271551