ZOJ月赛(0310) Problem C Travel along the Line
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
题意
在n步之内移动到m位置(可以假设向右),其中每步向左或向右走的概率是1/4,原地不动的概率是1/2。对于答案P/Q,输出P*Q^-1.
分析
若n
代码
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MOD = 1000000007;
const int MX = 100001;
ll P,Q,tmp,p,q,fac[MX];
int T,n,m;
ll fun(ll a,ll k) {
ll s=1;
while (k) {
if (k&1) s=s*a%MOD;
a=a*a%MOD;
k>>=1;
}
return s;
}
ll C(ll n, ll m) {
if (n<m) return 0;
return fac[n]*fun(fac[m]*fac[n-m]%MOD, MOD-2) % MOD;
}
int main() {
scanf("%d",&T);
fac[0]=1;
for (int i=1;i<=100000;++i) fac[i]=fac[i-1]*i%MOD;
while (T--) {
scanf("%d%d",&n,&m);
if (m < 0) m = -m;
if (m > n) {
printf("0\n");
continue;
}
P=0;
Q=fun(2,m+n);
for (int i=0; i<=(n-m)/2; ++i)
P = (P+fun(fun(4,i),MOD-2)*C(n,i)%MOD*C(n-i,m+i)) % MOD;
//printf("P=%lld\n",P);
tmp = __gcd(P,Q);
P/=tmp;
Q/=tmp;
P=P*fun(Q,MOD-2)%MOD;
printf("%lld\n",P);
}
return 0;
}
补充
DDN总结出一个很漂亮的公式:
C(2*n,n-|m|) / 4^n.
sixsixsix~