POJ 2779 DNA Sequence AC自动机+DP+矩阵
因为一个感叹号WA了一页
//#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<iostream> #include<sstream> #include<cmath> #include<climits> #include<string> #include<map> #include<queue> #include<vector> #include<stack> #include<set> using namespace std; typedef long long ll; typedef pair<int,int> pii; #define pb(a) push_back(a) #define INF 0x1f1f1f1f #define lson idx<<1,l,mid #define rson idx<<1|1,mid+1,r #define PI 3.1415926535898 template<class T> T min(const T& a,const T& b,const T& c) { return min(min(a,b),min(a,c)); } template<class T> T max(const T& a,const T& b,const T& c) { return max(max(a,b),max(a,c)); } void debug() { #ifdef ONLINE_JUDGE #else freopen("d:\\in.txt","r",stdin); // freopen("d:\\out1.txt","w",stdout); #endif } int getch() { int ch; while((ch=getchar())!=EOF) { if(ch!=' '&&ch!='\n')return ch; } return EOF; } const int MAX_NODE=100; const int SIGMA_SIZE=4; int ch[MAX_NODE][SIGMA_SIZE]; int fail[MAX_NODE]; int val[MAX_NODE]; int sz; int IDchar[26]; struct Matrix { int da[MAX_NODE][MAX_NODE]; Matrix(){memset(da,0,sizeof(da));} Matrix operator * (const Matrix &ans) { Matrix res; for(int i=0;i<sz;i++) { for(int j=0;j<sz;j++) { for(int k=0;k<sz;k++) res.da[i][j]=(res.da[i][j]+(ll)da[i][k]*ans.da[k][j])%100000; } } return res; } }; Matrix base; int idx(char c) { return IDchar[c-'A']; } void init() { memset(ch[0],0,sizeof(ch[0])); val[0]=0; sz=1; IDchar['A'-'A']=0; IDchar['C'-'A']=1; IDchar['G'-'A']=2; IDchar['T'-'A']=3; } void insert(const char *s) { int u=0; for(int i=0;s[i]!='\0';i++) { int v=idx(s[i]); if(!ch[u][v]) { memset(ch[sz],0,sizeof(ch[sz])); val[sz]=0; ch[u][v]=sz++; } u=ch[u][v]; } val[u]=1; } void construct() { fail[0]=0; queue<int> q; for(int c=0;c<SIGMA_SIZE;c++) if(ch[0][c]){fail[ch[0][c]]=0;q.push(ch[0][c]);} while(!q.empty()) { int r=q.front();q.pop(); for(int c=0;c<SIGMA_SIZE;c++) { int u=ch[r][c]; if(!u){ch[r][c]=ch[fail[r]][c];continue;} q.push(u); int v=fail[r]; while(v&&!ch[v][c])v=fail[v]; fail[u]=ch[v][c]; val[u]|=val[fail[u]]; } } } void constructMatrix() { memset(base.da,0,sizeof(base.da)); for(int u=0;u<sz;u++)if(!val[u]) { for(int c=0;c<SIGMA_SIZE;c++) { int v=ch[u][c]; if(!val[v]) base.da[u][v]++; } } } Matrix f(int n) { Matrix res=base; int k=31; while(!(n&(1<<k)))k--; while(k--) { res=res*res; if(n&(1<<k))res=res*base; } return res; } int main() { int n,m; while(scanf("%d%d",&n,&m)!=EOF) { init(); for(int i=1;i<=n;i++) { char s[100]; scanf("%s",s); insert(s); } construct(); constructMatrix(); Matrix res=f(m); int num=0; for(int i=0;i<sz;i++) num=(num+res.da[0][i])%100000; printf("%d\n",num); } return 0; }