ZOJ 4006 Travel along the Line

本文介绍了一道ZOJ月赛题目,要求计算在n步内以特定概率向左右移动或停留的情况下,达到指定位置的概率。通过组合数学的方法给出了求解思路及C/C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值