poj2778DNA Sequence (AC自动机+矩阵快速幂)

时间:2021-12-24 21:04:21

转载请注明出处: http://www.cnblogs.com/fraud/          ——by fraud

DNA Sequence
Time Limit: 1000MS   Memory Limit: 65536K

Description

It's well known that DNA Sequence is a sequence only contains A, C, T and G, and it's very useful to analyze a segment of DNA Sequence,For example, if a animal's DNA sequence contains segment ATC then it may mean that the animal may have a genetic disease. Until now scientists have found several those segments, the problem is how many kinds of DNA sequences of a species don't contain those segments.

Suppose that DNA sequences of a species is a sequence that consist
of A, C, T and G,and the length of sequences is a given integer n.

Input

First
line contains two integer m (0 <= m <= 10), n (1 <= n
<=2000000000). Here, m is the number of genetic disease segment, and n
is the length of sequences.

Next m lines each line contain a DNA genetic disease segment, and length of these segments is not larger than 10.

Output

An integer, the number of DNA sequences, mod 100000.

Sample Input

4 3
AT
AC
AG
AA

Sample Output

36

Source

题意
构造一个长度为n的DNA序列,要求其中不得出现m个禁止的字符串中的任意一个
一道很明显的矩阵快速幂的题。先通过AC自动机得出一个邻接矩阵,然后快速幂。
 #include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
#define REP(A,X) for(int A=0;A<X;A++)
#define MAXN 100010 int p[MAXN][];
int tail[MAXN];
int fail[MAXN];
int root,tot;
const long long MOD =;
struct Matrix{
int n;
int mat[][];
Matrix(){}
Matrix(int _n){
n=_n;
REP(i,n)
REP(j,n)mat[i][j]=;
}
void init()
{
REP(i,tot)
REP(j,tot)mat[i][j]=;
}
void unit()
{
REP(i,tot)
REP(j,tot)mat[i][j]=i==j?:;
}
Matrix operator *(const Matrix &a)const {
Matrix ret(n);
REP(i,n)
REP(j,n)
REP(k,n)
{
int tmp=(long long)mat[i][k]*a.mat[k][j]%MOD;
ret.mat[i][j]=(ret.mat[i][j]+tmp)%MOD;
}
return ret;
}
};
int newnode()
{
REP(i,)p[tot][i]=-;
tail[tot++]=;
return tot-;
}
void init()
{
tot=;
root=newnode();
}
int a[MAXN];
void insert(char *s){
int len=strlen(s);
REP(i,len)
{
if(s[i]=='A')a[i]=;
else if(s[i]=='C')a[i]=;
else if(s[i]=='G')a[i]=;
else if(s[i]=='T')a[i]=;
}
int now= root ;
REP(i,len)
{
if(p[now][a[i]]==-)p[now][a[i]]=newnode();
now=p[now][a[i]];
}
tail[now]++;
}
void build()
{
int now=root;
queue<int >q;
fail[root]=root;
REP(i,){
if(p[root][i]==-){
p[root][i]=root;
}
else {
fail[p[root][i]]=root;
q.push(p[root][i]);
}
}
while(!q.empty())
{
now =q.front();
q.pop();
if(tail[fail[now]])tail[now]=;
REP(i,){
if(p[now][i]==-){
p[now][i]=p[fail[now]][i];
}else{
fail[p[now][i]]=p[fail[now]][i];
q.push(p[now][i]);
}
}
}
}
char s[MAXN];
Matrix Mat;
int main()
{
ios::sync_with_stdio(false);
int n,m;
while(cin>>m>>n){
init();
REP(i,m){
cin>>s;
insert(s);
}
build();
Mat.n=tot;
Mat.init();
REP(i,tot){
REP(j,){
if(!tail[p[i][j]])Mat.mat[i][p[i][j]]++;
}
}
Matrix tmp(tot);
tmp.unit();
while(n){
if(n&)tmp=tmp*Mat;
Mat=Mat*Mat;
n>>=;
}
int ans=;
REP(i,tot)ans+=tmp.mat[][i];
ans%=MOD;
cout<<ans<<endl; }
return ;
}

代码君