题目描述
There is a knight - the chess piece - at the origin (0,0) of a two-dimensional grid.
When the knight is at the square (i,j), it can be moved to either (i+1,j+2) or (i+2,j+1).
In how many ways can the knight reach the square (X,Y)?
Find the number of ways modulo 109+7.
Constraints
·1≤X≤106
·1≤Y≤106
·All values in input are integers.
输入
Input is given from Standard Input in the following format:
X Y
输出
Print the number of ways for the knight to reach (X,Y) from (0,0), modulo 109+7.
样例输入 Copy
【样例1】
3 3
【样例2】
2 2
【样例3】
999999 999999
样例输出 Copy
【样例1】
2
【样例2】
0
【样例3】
151840682
提示
样例1解释
There are two ways: (0,0)→(1,2)→(3,3) and (0,0)→(2,1)→(3,3).
样例2解释
The knight cannot reach (2,2).
样例3解释
Print the number of ways modulo 109+7.
解析:
这两种走路得方式 (x+y)都得是3得倍数才行。
假设以第一种方式到达终点的方案为a
第二种方式到达终点的方案为b
那么答案就是C(a+b,a)或者 C(a+b,b);
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD=1e9+7;
const int N=2e6+10;
ll f[N];
ll a,b;
ll quick(ll a,ll b)
{
ll res=1;
while(b)
{
if(b&1) res=res*a%MOD;
a=a*a%MOD;
b>>=1;
}
return res;
}
int main()
{
cin>>a>>b;
if((a+b)%3||(2*a<b)||(2*b<a)) cout<<0<<endl;
else
{
ll k=(a+b)/3;
ll x=(2*b-a)/3;
f[0]=1;
for(int i=1;i<=k;i++) f[i]=f[i-1]*i%MOD;
cout<<(f[k]*quick(f[x],MOD-2)%MOD*quick(f[k-x],MOD-2)%MOD)<<endl;
}
}