BaoBao is traveling along a line with infinite length.
At the beginning of his trip, he is standing at position 0. At the beginning of each second, if he is standing at position , with probability he will move to position , with probability he will move to position , and with probability he will stay at position . Positions can be positive, 0, or negative.
DreamGrid, BaoBao's best friend, is waiting for him at position . BaoBao would like to meet DreamGrid at position after exactly seconds. Please help BaoBao calculate the probability he can get to position after exactly seconds.
It's easy to show that the answer can be represented as , where and are coprime integers, and is not divisible by . Please print the value of modulo , where is the multiplicative inverse of modulo .
Input
There are multiple test cases. The first line of the input contains an integer (about 10), indicating the number of test cases. For each test case:
The first and only line contains two integers and (). Their meanings are described above.
Output
For each test case output one integer, indicating the answer.
Sample Input
3
2 -2
0 0
0 1
Sample Output
562500004
1
0
題目鏈接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5724
題目大意:
初始位於位置0 要到達朋友的位置m 沒一步有三種走法 向左或者向右(概率分別爲 1/4 ) 停在原地(概率爲1/2) 問到達朋友所在位置的概率 p/q 輸出p*inv(q)%mod
分析:
從0點開始走向朋友m步 剩下n-m步 剩下的n-m步可分爲 停在原地 向左 向右 先選出有多少步停止 如果n-m爲奇數 那停的步數也爲奇數 否則爲偶數 先選停的步數再選向左或者向右的步數(左右無所謂) 中間過程分母用逆元
AC代碼:
#include <bits/stdc++.h>
#define lowbit(x) (x&-x)
#define gcd(a,b) __gcd(a,b)
#define mset(a,x) memset(a,x,sizeof(a))
#define FIN freopen("input","r",stdin)
#define FOUT freopen("output","w",stdout)
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const double eps=1e-6;
const int MAX=1e5+10;
const int mod=1e9+7;
typedef long long ll;
using namespace std;
inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
inline ll qpow(ll a,ll b){ll r=1,t=a; while(b){if(b&1)r=(r*t)%mod;b>>=1;t=(t*t)%mod;}return r;}
inline ll inv1(ll b){return qpow(b,mod-2);}
inline ll inv2(ll b){return b==1?1:(mod-mod/b)*inv2(mod%b)%mod;}
inline ll exgcd(ll a,ll b,ll &x,ll &y){if(!b){x=1;y=0;return a;}ll r=exgcd(b,a%b,y,x);y-=(a/b)*x;return r;}
int dir[4][2]={0,1,1,0,0,-1,-1,0};
ll fac[1000005];
void init(){
fac[0]=fac[1]=1;
for (int i=2;i<=1000000;i++) fac[i]=fac[i-1]*i%mod;
}
ll C(ll n,ll m){
return fac[n]*inv2(fac[m])%mod*inv2(fac[n-m])%mod;
}
int main (){
int t;
init();
scanf ("%d",&t);
while (t--){
ll n,m,temp;
scanf ("%lld%lld",&n,&m);
m=(m>=0?m:-m);
ll sum=0;
temp=n-m;
if(temp%2){
ll left,right;
for (ll i=1;i<=temp;i+=2){
left=(temp-i)/2;
right=left+m;
sum=(sum+C(n,i)*C(n-i,left)%mod*inv2(qpow(2,n+left+right)%mod))%mod;
}
}
else {
ll left,right;
for (ll i=0;i<=temp;i+=2){
left=(temp-i)/2;
right=left+m;
sum=(sum+C(n,i)*C(n-i,left)%mod*inv2(qpow(2,n+left+right)%mod))%mod;
}
}
printf ("%lld\n",sum%mod);
}
return 0;
}