题解:P4958 [COCI 2017/2018 #6] Mate
WhiteSilver · · 题解
今天的模拟赛 T1。
思路:
首先我们可以先看
考虑用后缀和预处理该位置后面的
前面直接组合数算取
代码:
#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;
}