题解 [ABC271G] Access Counter

· · 题解

一眼矩阵加速,但是补题的时候对于转移方程的构造想了好久。

注意到我们转移的时候其实只关注两点:当前所在的小时,以及当前 access 了几次。

所以我们不妨设 dp_{i,j} 表示当前 access 了 i 次,且最后一次 access 是在第 j 个小时进行的。而 i 这一维我们是要矩阵加速转移的,所以我们只需要考虑 j 这一维怎么转移。也就是,如果从第 i 个小时 access 之后,一直不 access,直到不知道多少天之后又在第 j 个小时 access 了的概率是多少。

我们不妨设 p_i 为第 i 个小时 access 的概率,s_{i,j} 为从第 i 个小时转移到第 j 个小时的概率,n 为过去的整数天数,sum_{i,j} 为从第 i 个小时到第 j 个小时都不 access 的概率。则有方程:

s_{i,j}=\sum_{n=0}^{+\infty}sum_{i+1,j-1}p_i\times sum_{1,24}^n

于是就是一个等比数列求和的形式,转化一下就是:

s_{i,j}=\dfrac{sum_{i+1,j-1}p_i}{1-sum_{1,n}}

于是把它扔进矩阵,套路矩阵加速即可。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define int long long
const int N=24;
const int mod=998244353;
const int hun=828542813;
int n,q,p,s=1;
char in[N+1];
struct node{
    int a[N][N];
    node(){
        memset(a,0,sizeof(a));
    }
    void init(){
        for (int i=0;i<N;i++)
            a[i][i]=1;
    }
}S,Z;
node operator *(const node&x,const node&y){
    node z;
    for (int k=0;k<N;k++)
        for (int i=0;i<N;i++)
            for (int j=0;j<N;j++)
                z.a[i][j]=(z.a[i][j]+x.a[i][k]*y.a[k][j]%mod)%mod;
    return z;
}
ll read(){
    ll w=0,f=1;
    char c=getchar();
    while (c>'9'||c<'0'){
        if (c=='-') f=-1;
        c=getchar();
    }
    while (c>='0'&&c<='9'){
        w=(w<<3)+(w<<1)+(c^48);
        c=getchar();
    }
    return w*f;
}
ll ksm(ll x,ll y){
    ll ans=1;
    while (y){
        if (y&1) ans=ans*x%mod;
        x=x*x%mod;
        y>>=1;
    }
    return ans;
}
ll inv(ll x){
    x=(x%mod+mod)%mod;
    return ksm(x,mod-2);
}
ll chan(int pos,bool flag){
    if (!flag){
        if (in[pos]=='T') return q*hun%mod;
        return p*hun%mod;       
    }else{
        if (in[pos]=='T') return (100-q)*hun%mod;
        return (100-p)*hun%mod;
    }
}
node ksm_(node x,int y){
    node ans;
    ans.init();
    while (y){
        if (y&1) ans=ans*x;
        x=x*x;
        y>>=1;
    }
    return ans;
}
signed main(){
    n=read(),q=read(),p=read();
    scanf("%s",in);
    for (int i=0;i<N;i++){
        s=s*chan(i,1)%mod;
    }
    for (int i=0;i<N;i++){
        for (int j=0;j<N;j++){
            if (i<j){
                int now=1;
                for (int k=i+1;k<j;k++) now=now*chan(k,1)%mod;
                now=now*chan(j,0)%mod;
                Z.a[i][j]=now*inv(1-s)%mod;
            }else{
                int now=1;
                for (int k=i+1;k<N;k++) now=now*chan(k,1)%mod;
                for (int k=0;k<j;k++) now=now*chan(k,1)%mod;
                now=now*chan(j,0)%mod;
                Z.a[i][j]=now*inv(1-s)%mod;
            }
        }
    }
    for (int i=0;i<N;i++)
        S.a[0][i]=Z.a[N-1][i];
    Z=ksm_(Z,n-1);
    S=S*Z;
    int ans=0;
    for (int i=0;i<N;i++){
        if (in[i]=='A') ans=(ans+S.a[0][i])%mod;
    }
    cout<<ans<<'\n';
    return 0;
}