问题 D: Knight--------------------------思维(组合数学)

题目描述
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;
    }
 } 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值