2020阿里笔试——春季实习第二场
第一题:
从n个人中选择任意数量的人员组成一支队伍,然后从一支队伍中选出一位队长,不同的队长算不同的组合,问这样的组合的数量对10^9+7取模 。
数据范围:1 <= n <= 1000000000;
示例
输入:n = 2
输出:4
解释,(1),(2)(1,2),(2,1)四种,括号第一个为队长
推导公式,n∗2^(n−1)求2的幂
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<iostream> #include<vector> #include<string> #include<stdlib.h> #include<map> using namespace std; #define MAX 999999 /*int pow_mod(int a,int b,int md) { int ans=1,base=a%md; while(b) { if(b&1) ans=(long long)ans*base%md; base=(long long)base*base%md; b>>1; } return ans; }*/ long long pow_mod(int a, long long n, long long m) { if(n==0) return 1; long long half=pow_mod(a,n/2,m); if(n%2==0) return (long long)half*half%m; else return (long long)half*half*a%m; } int main() { int N; cin>>N; cout<<(N*pow_mod(2,N-1,1000000007))%1000000007; return 0; }
第二题:
一个地图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步
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<iostream> #include<vector> #include<string> #include<stdlib.h> #include<map> #include<queue> using namespace std; #define MAX 999999 int dp[500][500],lable[500][500]; int N,M; int start_i,start_j,end_i,end_j; struct node { int i; int j; int deep; }; int dir[]={0,1,0,-1,1,0,-1,0}; queue<struct node>result; int bfs() { while(result.size()) { struct node now=result.front(); result.pop(); if(now.i==end_i&&now.j==end_j) return now.deep; for(int i=0;i<8;i+=2) { if(now.i+dir[i]>=0&&now.i+dir[i]<M&&now.j+dir[i+1]>=0&&now.j+dir[i+1]<N&&dp[now.i+dir[i]][now.j+dir[i+1]]==1&&lable[now.i+dir[i]][now.j+dir[i+1]]==0) { lable[now.i+dir[i]][now.j+dir[i+1]]=1; struct node tmp; tmp.i=now.i+dir[i]; tmp.j=now.j+dir[i+1]; tmp.deep=now.deep+1; result.push(tmp); } } struct node tp; tp.i=M-1-now.i; tp.j=N-1-now.j; tp.deep=now.deep+1; if(dp[tp.i][tp.j]==1&&lable[tp.i][tp.j]==0) { lable[tp.i][tp.j]=1; result.push(tp); } } return 0; } int main() { cin>>M>>N; for(int i=0;i<M;i++) { for(int j=0;j<N;j++) { char tmp; cin>>tmp; if(tmp=='S') { dp[i][j]=1; start_i=i; start_j=j; } else if(tmp=='E') { dp[i][j]=1; end_i=i; end_j=j; } else if(tmp=='.') dp[i][j]=1; else dp[i][j]=0; } } /*for(int i=0;i<M;i++) { for(int j=0;j<N;j++) cout<<dp[i][j]; cout<<endl; } cout<<endl<<endl;*/ struct node start; start.i=start_i;start.j=start_j;start.deep=0; lable[start_i][start_j]=1; result.push(start); cout<<bfs()<<endl; return 0; } /* 4 4 #S.. E#.. .... .... */
附:
leetcode 50. Pow(x, n)
快速幂模板!
class Solution { public: double fast_pow(double x, long long n) { if(n==0) return 1.0; double half=fast_pow(x,n/2); if(n%2==0) return half*half; return x*half*half; } double myPow(double x, long long n) { if(n<0) { n*=-1; x=1/x; } return fast_pow(x,n); } };