修改了表述错误。
有一些长度为 的由 种不同字符构成的字符串,其中有 个约束条件,每个约束条件给定一个字符对 ,要求在字符串中不能有字符 在字符 之后出现,求满足这些约束条件的所有字符串的个数。
设 为前 个字符,第 个字符为 的方案数, 为字符 是否能在字符 后面出现,有:
时间复杂度 ,不可过。
看见这个式子很像矩阵乘法的样子,所以考虑矩阵快速幂优化,矩阵的每一位 表示字符 是否能在字符 后面出现。
初始有:,转移 次即可,所以答案数组为:
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define rint register int
#define int long long
using namespace std;
namespace IO{
#define File(x,y) freopen(#x,"r",stdin),freopen(#y,"w",stdout);
inline int read(){
int w=0,f=1; char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-') f=-1; ch=getchar();}
while(ch>='0'&&ch<='9'){w=(w<<3)+(w<<1)+(ch^48); ch=getchar();}
return w*f;
}
inline void write(int x){
static int sta[35]; int top=0;
do{sta[++top]=x%10,x/=10;}while(x);
while(top) putchar(sta[top--]+48); puts("");
}
}
using namespace IO;
namespace CL{
#define fill(x,y) memset(x,y,sizeof(x))
#define copy(x,y) memcpy(y,x,sizeof(x))
const int maxn=60,mod=1e9+7;
int n,m,k,ans;
char s[2];
namespace Matrix{
struct matrix{
int p[maxn][maxn];
matrix(){fill(p,0);}
inline void build(){for(int i=1;i<=55;i++) p[i][i]=1;}
matrix operator *(const matrix &x)const{
matrix res;
for(int i=1;i<=55;i++)
for(int j=1;j<=55;j++)
for(int k=1;k<=55;k++)
res.p[i][j]=(res.p[i][j]+1ll*p[i][k]*x.p[k][j]%mod)%mod;
return res;
}
}trans,f;
matrix qpow(matrix x,int y){
matrix res; res.build();
while(y){
if(y&1) res=res*x;
x=x*x;
y>>=1;
}
return res;
}
}using namespace Matrix;
inline int id(char x){
if(x>='a' && x<='z') return x-96;
if(x>='A' && x<='Z') return x-38;
}
inline int main(){
n=read(); m=read(); k=read();
for(int i=1;i<=m;i++)
for(int j=1;j<=m;j++)
trans.p[i][j]=1;
for(int i=1;i<=k;i++){
scanf("%s",s);
trans.p[id(s[0])][id(s[1])]=0;
}
for(int i=1;i<=m;i++) f.p[1][i]=1;
trans=qpow(trans,n-1);
f=f*trans;
for(int i=1;i<=m;i++) ans=(ans+f.p[1][i])%mod;
printf("%lld\n",ans);
return 0;
}
}
signed main(){return CL::main();}