View Code
#define ROOT 0 const int MAX_NODE=100100;//stringnum*stringlen const int CHI=26; //儿子数 struct ACtree { int size; int hash[300]; int val[MAX_NODE]; int fail[MAX_NODE]; int SQ[MAX_NODE]; int chd[MAX_NODE][CHI]; void get_hash() { int i,j,k; for(i=0;i<CHI;i++) hash[i+'A']=i; //只有大写,小写A->a,可见字符A->32,CHI-128 } void init() { size=fail[0]=0; memset(val,0,sizeof(val)); memset(chd[0],0,sizeof(chd)); } void insert(char *str,int k) { int i,j,id,p=ROOT; for(i=0;str[i];i++) { id=hash[str[i]]; if(!chd[p][id]) { chd[p][id]=++size; memset(chd[size],0,sizeof(chd[size])); } p=chd[p][id]; } val[p]=k; } void build() { int i,j,k,id,p=ROOT,r,v; int qhead,qtail; qhead=qtail=0; for(i=0;i<CHI;i++) { if(chd[p][i]) { SQ[qtail++]=chd[p][i]; fail[chd[p][i]]=ROOT; } } while(qhead!=qtail) { r=SQ[qhead++]; for(i=0;i<CHI;i++) { v=chd[r][i]; if(v) SQ[qtail++]=v,fail[v]=chd[fail[r]][i]; else chd[r][i]=chd[fail[r]][i]; } } } void solve(char *str) { int p=ROOT; for(int i=0;str[i];i++) { int id=hash[str[i]]; p=chd[p][id]; int tmp=p; while(tmp!=ROOT) { if(val[tmp]) //find one tmp=fail[tmp]; //continue } } } //solve }AC; void get_data() { char str[100]; AC.init(); for(int i=1;i<=M;i++) { scanf("%s",str); AC.insert(str,i); } } void solve() { AC.build(); AC.solve(); } int main() { AC.get_hash(); return 0; }