未写完,待补档
缺一个快速幂
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;
struct Trie
{
int next[200][5],fail[200],end[200];
int cm[200][200],ccm[200][200];//状态图邻接矩阵
//状态总数等于子串数量乘以子串长度
//trie的边数next等于状态总数*单个状态数
//每种状态对应一个fail
//每种状态只有一种输出end
int root,L,K;
int newnode()
{
for(int i = 0; i < 4; i++)
next[L][i] = -1;
end[L++] = 0;
return L-1;
}
void init()
{
L = 0;
root = newnode();
}
void insert(char buf[])
{
int len = strlen(buf);
int now = root;
for(int i = 0; i < len; i++)
{
if(next[now][buf[i]-'0'] == -1)
next[now][buf[i]-'0'] = newnode();
now = next[now][buf[i]-'0'];
}
end[now]++;
}
void build()
{
queue<int>Q;
fail[root] = root;
for(int i = 0; i < 4; i++)
if(next[root][i] == -1)
next[root][i] = root;
else
{
fail[next[root][i]] = root;
Q.push(next[root][i]);
}
while( !Q.empty() )
{
int now = Q.front();
Q.pop();
for(int i = 0; i < 4; 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 query(char buf[])
{
int len = strlen(buf);
int now = root;
int res = 0;
for(int i = 0; i < len; i++)
{
now = next[now][buf[i]-'0'];
int temp = now;
while( temp != root )
{
res += end[temp];
end[temp] = 0;
temp = fail[temp];
}
}
return res;
}
void debug()
{
for(int i = 0; i < L; i++)
{
printf("id = %3d,fail = %3d,end = %3d,chi = [",i,fail[i],end[i]);
for(int j = 0; j < 4; j++)
printf("%2d",next[i][j]);
printf("]\n");
}
for(int i = 0; i < L; i++){
for(int j = 0; j < L; j++)
printf(" %d",cm[i][j]);
printf("\n");
}
for(int i = 0; i < K; i++){
for(int j = 0; j < K; j++)
printf(" %d",ccm[i][j]);
printf("\n");
}
}
void build_matrix(){
memset(cm,0,sizeof(cm));
for(int i = 0; i < L; i++){
for(int j = 0; j < 4; j++){
cm[i][next[i][j]]++;
}
}
}
void matrix_cut(){
bool cut[200]={0};
for(int i = 0; i < L; i++){
if(end[i]==1||end[fail[i]]){
cut[i]=1;K++;
}
}
K=L-K;
int p=0;
for(int i=0;i<K;i++,p++){
while(cut[p]) p++;
int q=0;
for(int j=0;j<K;j++,q++){
while(cut[q]) q++;
ccm[i][j]=cm[p][q];
}
}
}
};
char buf[15];
Trie ac;
void change(){
int len=strlen(buf);
for(int i=0;i<len;i++)
if(buf[i]=='A')
buf[i] = '0';
else if(buf[i]=='C')
buf[i] = '1';
else if(buf[i]=='T')
buf[i] = '2';
else
buf[i] = '3';
}
struct Matrix
{
unsigned long long mat[40][40];
int n;
Matrix(){}
Matrix(int _n)
{
n=_n;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
mat[i][j] = 0;
}
Matrix operator *(const Matrix &b)const
{
Matrix ret = Matrix(n);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int k=0;k<n;k++)
ret.mat[i][j]+=mat[i][k]*b.mat[k][j];
return ret;
}
};
int main()
{
int n,m;
while( ~scanf("%d %d",&n,&m) )
{
ac.init();
for(int i = 0; i < n; i++)
{
scanf("%s",buf);
change();
ac.insert(buf);
// ac.debug();
}
ac.build();
ac.build_matrix();
ac.matrix_cut();
ac.debug();
scanf("%s",buf);
printf("%d\n",ac.query(buf));
}
return 0;
}