【矩阵】[BALKAN OI 2009][Z_trening - 718][CQBZOJ2811]READING
题目
分析:
1.由于矩阵只能限制路径的边数,不能限制长度,我们将一个字母拆成5个点,来限制长度;
2.通过在开头添加到任何字符差异度都为1的虚拟字符,来枚举长度比n小的单词;
#include<cstdio>
#include<algorithm>
#include<cstring>
#define MOD 1000000007
using namespace std;
#define MAXC 26
#define MAXLEN 5
#define MAXM MAXC*MAXLEN
typedef int matrix[MAXM+1][MAXM+1];
int n,m,len;
matrix ans;
void Read(int &x){
char c;
while(c=getchar(),c!=EOF)
if(c>='0'&&c<='9'){
x=c-'0';
while(c=getchar(),c>='0'&&c<='9')
x=x*10+c-'0';
ungetc(c,stdin);
return;
}
}
void read(){
int i,j;
char a[2],b[2];
Read(n),Read(m);
for(i=0;i<MAXC;i++)
for(j=1;j<MAXLEN;j++)
ans[i*MAXLEN+j][i*MAXLEN+j+1]=1;
for(i=0;i<MAXC;i++)
for(j=i;j<MAXC;j++)
ans[i*MAXLEN+1][j*MAXLEN+1]=ans[j*MAXLEN+1][i*MAXLEN+1]=1;
for(i=1;i<=m;i++){
scanf("%s%s",a,b);
a[0]-='a',b[0]-='a';
Read(len);
ans[a[0]*MAXLEN+1][b[0]*MAXLEN+1]=ans[b[0]*MAXLEN+1][a[0]*MAXLEN+1]=0;
ans[a[0]*MAXLEN+len][b[0]*MAXLEN+1]=ans[b[0]*MAXLEN+len][a[0]*MAXLEN+1]=1;
}
for(i=0;i<MAXC;i++)
ans[0][i*MAXLEN+1]=1;
ans[0][0]=1;
}
void mul(matrix a,matrix b,matrix c){
matrix d;
memset(d,0,sizeof d);
int i,j,k;
for(i=0;i<=MAXM;i++)
for(j=0;j<=MAXM;j++)
for(k=0;k<=MAXM;k++)
d[i][j]=(d[i][j]+1ll*a[i][k]*b[k][j])%MOD;
memcpy(c,d,sizeof d);
}
void quick_pow(matrix a,int b,matrix c){
matrix t,d;
memcpy(t,a,sizeof t);
memset(d,0,sizeof d);
for(int i=0;i<=MAXM;i++)
d[i][i]=1;
while(b){
if(b&1)
mul(d,t,d);
mul(t,t,t);
b>>=1;
}
memcpy(c,d,sizeof d);
}
void print(){
int i,j,ret=0;
for(i=0;i<MAXC;i++)
ret=(ret+ans[0][i*MAXLEN+1])%MOD;
for(i=0;i<MAXC;i++)
for(j=0;j<MAXC;j++)
ret=(ret+ans[i*MAXLEN+1][j*MAXLEN+1])%MOD;
printf("%d\n",ret);
}
int main()
{
read();
quick_pow(ans,n,ans);
print();
}