Travel along the Line
Problem Description
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 x, with 1 4 \frac{1}{4} 41 probability he will move to position (x-1), with 1 4 \frac{1}{4} 41 probability he will move to position (x-1), and with 1 2 \frac{1}{2} 21 probability he will stay at position x. Positions can be positive, 0, or negative.
DreamGrid, BaoBao’s best friend, is waiting for him at position m. BaoBao would like to meet DreamGrid at position m after exactly n seconds. Please help BaoBao calculate the probability he can get to position m after exactly n seconds.
It’s easy to show that the answer can be represented as P Q \frac{P}{Q} QP, where P and Q are coprime integers, and Q is not divisible by 1 0 9 + 7 10^9+7 109+7 . Please print the value of P Q − 1 PQ^{-1} PQ−1 modulo 1 0 9 + 7 10^9+7 109+7, where Q − 1 Q^{-1} Q−1 is the multiplicative inverse Q of modulo 1 0 9 + 7 10^9+7 109+7.
Input
There are multiple test cases. The first line of the input contains an integer T (about 10), indicating the number of test cases. For each test case:
The first and only line contains two integers n and m( 0 ≤ n , ∣ m ∣ ≤ 1 0 5 0 \le n,|m| \le 10^5 0≤n,∣m∣≤105). 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
题意
在位置x,下一秒有 1 4 \frac{1}{4} 41的概率移动至x-1,有 1 4 \frac{1}{4} 41的概率移动至x+1,有 1 2 \frac{1}{2} 21的概率留在原地。初始位置在0,求n秒处于m的概率。
题解:
设n秒向
x
−
1
x-1
x−1方向移动了
i
i
i次,向
x
+
1
x+1
x+1方向移动了
j
j
j次,停留在原地
k
k
k次(
i
≥
0
,
j
≥
0
,
k
≥
0
,
i
+
j
+
k
=
n
i\ge0,j\ge0,k\ge0,i+j+k=n
i≥0,j≥0,k≥0,i+j+k=n)。要停留在位置m,则显然
i
−
j
=
m
i-j=m
i−j=m。
则概率为
∑
C
i
+
j
n
∗
C
i
+
j
j
∗
2
k
4
n
\frac{\sum C^n_{i+j}*C^j_{i+j}*2^k}{4^n}
4n∑Ci+jn∗Ci+jj∗2k,暴力所有的i,求和即可。
#include<stdio.h>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<ctype.h>
#include<cstring>
#include<map>
#include<vector>
#include<queue>
#define dbg(x) cout<<#x<<" = "<<x<<endl;r
#define INF 0x3f3f3f3f
#define LLINF 0x3f3f3f3f3f3f3f3f
#define eps 1e-6
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int maxn = 100200;
const int mod = 1000000007;
LL jie[maxn];
LL Pow(LL a, LL b);
LL C(LL n, LL m);
int main()
{
int t, n, m, i, j, k;
jie[0] = 1;
for(i=1;i<=100004;i++)
jie[i] = jie[i-1]*i%mod;
scanf("%d", &t);
while(t--)
{
scanf("%d %d", &n, &m);
LL up = 0, dn = Pow(4, n);
m = abs(m);
for(i=0;2*i+m<=n;i++)
up = (up+(C(2*i+m, i)*C(n, n-2*i-m)%mod)*Pow(2, n-2*i-m)%mod)%mod;
printf("%lld\n", up*Pow(dn, mod-2)%mod);
}
return 0;
}
LL C(LL n, LL m)
{
LL ans = (jie[n]*Pow(jie[m], mod-2)%mod) * Pow(jie[n-m], mod-2)%mod;
return ans;
}
LL Pow(LL a, LL b)
{
LL n = 1;
while(b)
{
if(b&1)n = n*a%mod;
a = a*a%mod;
b/=2;
}
return n;
}