[蓝桥杯 2022 省 A] 爬树的甲壳虫

概率dp,关键是要走出思维定势:

一般来讲,都会把dp[i]定义为从0爬到高度i的概率,但是因为任何时刻都有掉下去的可能,这样子不好推(也有大佬这样做出来的)

我们把dp[i]定义为从i爬到n的概率,公式就好推了

而且,我们可以根据定义很自然地得到:

dp[n]=0

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;

inline int read()
{
    int x = 0, f = 1; char ch = getchar();
    while(ch < '0' || ch > '9') 
    {
        if(ch == '-') f = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
    {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

const LL P = 998244353;

int n;

LL quick_pow(LL a, LL k)
{
    LL res = 1;
    while(k)
    {
        if(k&1) res = res*a%P;
        a = a * a % P;
        k>>=1;
    }
    return res;
}

int main()
{
    n = read();
    LL k1 = 1, k2 = 0, k3 = 0;
    for(int i = 1; i <= n; i++)
    {
        int a = read(), b = read();
        LL p_fall = 1ll*a*quick_pow(1ll*b, P-2) % P;
        LL p_up = 1ll*(b-a)*quick_pow(1ll*b, P-2) % P;
        k3 = (k3 + k1) % P;
        k2 = (k2 + p_fall * k1 % P) % P;
        k1 = (k1 * p_up) % P;
    }
    LL t = quick_pow(1ll-k2, P-2);
    t=(t%P+P)%P;
    printf("%lld",k3*t%P);
    return 0;
}

一开始过不了样例,对着main函数看了半天,最后才发现问题在快速幂里😂

一开始把

if(k&1) res = res*a%P;
        a = a * a % P;

这两句的顺序写反了,先倍增a,然后才更新res,导致快速幂的结果错误

posted @ 2024-04-12 12:15  Gold_stein  阅读(2)  评论(0编辑  收藏  举报