题意:检测所有可能的n位DNA串有多少个DNA串中不含有指定的病毒片段
思路:ac自动机+矩阵快速幂,具体请参考http://hi.baidu.com/ccsu_010/item/7847a3c17f6fe2bc0d0a7b89
感谢然哥的ac自动机的模版 http://blog.csdn.net/zz_1215/article/category/1145295
#include <iostream>
#include <string>
#include <cstring>
#include <queue>
using namespace std;
#define ll long long
const int mod=100000;
const int maxn=205;
const int head=0;
const int kind=4;
int n,m,use;
queue <int> q;
struct node
{
int to[kind];
int fail;
int flag;
}zx[maxn];
struct matrix
{
ll tx[maxn][maxn];
};
int get()
{
use++;
zx[use].fail=zx[use].flag=0;
memset(zx[use].to,-1,sizeof(zx[use].to));
return use;
}
int ex(char t)
{
if(t=='A') return 0;
if(t=='T') return 1;
if(t=='G') return 2;
if(t=='C') return 3;
return -1;
}
void insert(string p)
{
int now = head,c;
for(int i=0;i<p.length();++i)
{
c=ex(p[i]);
if(zx[now].to[c]==-1) zx[now].to[c]=get();
now = zx[now].to[c];
}
zx[now].flag = 1;
return;
}
void build()
{
while(!q.empty()) q.pop();
q.push(0);
int now ,to,temp,kk;
while(!q.empty())
{
now = q.front();
q.pop();
for(int i=0;i<kind;++i)
{
if(zx[now].to[i]!=-1)
{
to = zx[now].to[i];
q.push(to);
temp = now;
while(temp)
{
temp = zx[now].fail;
if(zx[temp].to[i]!=-1)
{
zx[to].fail=zx[temp].to[i];
kk=zx[temp].to[i];
if(zx[kk].flag)zx[to].flag=zx[kk].flag;
break;
}
}
}
else
{
temp = now;
while(temp)
{
temp = zx[temp].fail;
if(zx[temp].to[i]!=-1)
{
temp=zx[temp].to[i];
break;
}
}
zx[now].to[i]=temp;
}
}
}
return;
}
matrix mul(matrix k1,matrix k2)
{
matrix kk;
for(int i=0;i<=use;++i)
for(int j=0;j<=use;++j)
kk.tx[i][j]=0;
for(int i=0;i<=use;++i)
{
for(int j=0;j<=use;++j)
{
for(int e=0;e<=use;++e)
{
kk.tx[i][j]=(k1.tx[i][e]*k2.tx[e][j]+kk.tx[i][j])%mod;
}
}
}
return kk;
}
matrix n_mul(matrix k,int t)
{
matrix zz;
for(int i=0;i<=use;++i)
for(int j=0;j<=use;++j)
{
if(i==j) zz.tx[i][j]=1;
else zz.tx[i][j]=0;
}
while(t)
{
if(t&1) zz=mul(zz,k);
t=t>>1;
k=mul(k,k);
}
return zz;
}
int main()
{
string str;
ll ans;
matrix a;
int to,temp;
while(cin>>m>>n)
{
use=-1;
ans=0;
get();
for(int i=0;i<maxn;++i)
for(int j=0;j<maxn;++j)
a.tx[i][j]=0;
for(int i=1;i<=m;++i)
{
cin>>str;
insert(str);
}
build();
for(int i=0;i<=use;++i)
{
for(int j=0;j<kind;++j)
{
to = zx[i].to[j];
if(zx[i].flag!=1&&zx[to].flag!=1) a.tx[i][to]++;
}
}
a=n_mul(a,n);
for(int i=0;i<=use;++i) ans+=a.tx[0][i];
cout<<ans%mod<<endl;
}
return 0;
}
ps:我写的太挫卡过--!