题意:
给出n个串,现在要求长度为L的串至少包含着n个串中的两个串的个数。
题解:
一看这种计数类问题要么dp,要么矩阵乘法。dp明显内存时间都爆。那么可以考虑用矩阵乘法,首先如果直接用矩阵存不包含任意n个字符串,L次幂,将maze[0][i]相加得到长度为L的不包含任何n个串对应串的个数,然后在计算全部的情况,这样就缺包含一个字符串对应串的个数这个方案了,之前用枚举N个字符串哪个出现了进行矩阵乘法,因为n很小啊,但是答案不对。看了大牛题解,可以构造这样的矩阵,矩阵规模是2倍的节点数,构成类似这样的矩阵:
| 1 1 |
| 0 1 |
第二行的是辅助作用,第一象限是只包含一个串的情况,第二象限是不包含串的情况。其实认真想想发现很巧妙,因为在乘法时,总可能出现从第一矩阵走到第二个矩阵的情况,这种情况相当于不包含任何n个字符串的路劲走了一个包含一个字符串的路劲,这样就变成了之包含一个字符串的路径。
#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#include<queue>
#include<map>
#include<set>
using namespace std;
#define B(x) (1<<(x))
typedef long long ll;
//typedef unsigned __int64 Ull;
const int oo=0x3f3f3f3f;
//const ll OO=1LL<<61;
const int MOD=10007;
const int maxn=10;
const int SIZE=33;
const int type=4;
char str[maxn];
map<char,int>mat;
struct Matrix
{
int maze[SIZE<<1][SIZE<<1],n;
Matrix(){}
Matrix(int n_)
{
this->n=n_;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
maze[i][j]=0;
}
Matrix operator*(const Matrix& a)const
{
Matrix c(a.n);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
c.maze[i][j]+=maze[i][k]*a.maze[k][j];
c.maze[i][j]%=MOD;
}
return c;
}
Matrix operator^(int k)
{
Matrix a=*this;
Matrix ans(a.n);
for(int i=0;i<ans.n;i++)
ans.maze[i][i]=1;
while(k)
{
if(k&1)
ans=ans*a;
a=a*a;
k>>=1;
}
return ans;
}
};
int quick_pow(int a,int k)
{
int ans=1;
while(k)
{
if(k&1)
ans=ans*a%MOD;
a=a*a%MOD;
k>>=1;
}
return ans;
}
struct ACautomaton
{
int next[SIZE][type],fail[SIZE],word[SIZE];
int cnt,root;
int newNode()
{
for(int i=0;i<type;i++)
next[cnt][i]=-1;
word[cnt++]=0;
return cnt-1;
}
void Init()
{
cnt=0;
root=newNode();
}
void Insert(char buff[])
{
int now=root;
for(int i=0,k;buff[i];i++)
{
k=mat[buff[i]];
if(next[now][k]==-1)
next[now][k]=newNode();
now=next[now][k];
}
word[now]=1;
}
void build()
{
fail[root]=root;
int now=root;
queue<int>Q;
for(int i=0;i<type;i++)
{
if(next[now][i]==-1)
next[now][i]=root;
else
{
fail[next[now][i]]=root;
Q.push(next[now][i]);
}
}
while(!Q.empty())
{
now=Q.front();
Q.pop();
if(word[fail[now]]) word[now]=1;
for(int i=0;i<type;i++)
{
if(next[now][i]==-1)
next[now][i]=next[fail[now]][i];
else
{
fail[next[now][i]]=next[fail[now]][i];
Q.push(next[now][i]);
}
}
}
}
int solve(int L)
{
Matrix a(cnt*2);
for(int i=0;i<cnt;i++)
for(int j=0;j<type;j++)
{
int k=next[i][j];
if(word[k])
a.maze[i][k+cnt]++;
else
{
a.maze[i][k]++;
a.maze[i+cnt][k+cnt]++;
}
}
a=a^L;
int ans=quick_pow(4,L);
for(int i=0;i<a.n;i++) ans=(ans-a.maze[0][i]+MOD)%MOD;
return ans;
}
}ac;
int main()
{
int N,L;
mat['A']=0;mat['T']=1;mat['C']=2;mat['G']=3;
while(scanf("%d %d",&N,&L)!=EOF)
{
ac.Init();
for(int i=1;i<=N;i++)
{
scanf("%s",str);
ac.Insert(str);
}
ac.build();
cout<<ac.solve(L)<<endl;
}
return 0;
}
/**
*/