题解:P4958 [COCI 2017/2018 #6] Mate

· · 题解

今天的模拟赛 T1。

思路:

首先我们可以先看 XY 的方案数,先找到 X,再从这个位置出发找 Y。这样显然会超时。

考虑用后缀和预处理该位置后面的 Y 的个数,这样可以做到线性。每次查询 O(1)。

前面直接组合数算取 D - 2 个字符的方案数,乘以后面 XY 的方案数即为答案。

代码:

#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define gc getchar
#define pc putchar
#define pb push_back
#define ls u<<1
#define rs u<<1|1
const int ri=500005,P=1e9+7;
template<typename T>inline void read(T&x){x=0;int f=1;char ch=gc();while(!isdigit(ch)){if(ch=='-') f=-1;ch=gc();}while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=gc();}x*=f;}
template<typename T,typename ...T1>inline void read(T&x,T1&...x1){read(x);read(x1...);}
string s,xy;
LL Q,d,cnt;
LL f[ri],g[ri],suf[ri];
LL qsm(LL a,LL b){
    LL res=1;
    for(;b;a=a*a%P,b>>=1) if(b&1)res=res*a%P;
    return res%P;
}
LL C(LL n,LL m){
    return f[n]*g[m]%P*g[n-m]%P;
}
int main(){
    cin>>s>>Q;
    f[0]=g[0]=1;
    for(LL i=1;i<2000;i++){
        f[i]=f[i-1]*i%P;
        g[i]=qsm(f[i],P-2)%P;
    }
    while(Q--){
        cin>>d>>xy;
        suf[s.size()]=0;
        for(int i=s.size()-2;i>=d-2;i--){
            suf[i]=suf[i+1]+(s[i+1]==xy[1]);
            //cout<<i<<endl;
        }
        for(int i=d-2;i<s.size()-1;i++){
            if(s[i]==xy[0]){
                LL pre=C(i,d-2)%P;
                //cout<<"C "<<i-1<<" "<<d-2<<":"<<pre<<endl;
                cnt=(cnt+pre*suf[i])%P;
            }
        }
        printf("%lld\n",cnt%P);
        cnt=0;
    }
    return 0;
}