标签:des style blog http color os io java strong
先上题目:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 215 Accepted Submission(s): 140
1 #include <cstdio> 2 #include <cstring> 3 #include <queue> 4 #define MAX 10002 5 using namespace std; 6 7 struct Trie{ 8 int next[MAX][26],fail[MAX],end[MAX],num[MAX][26]; 9 int root,L; 10 11 int newnode(){ 12 for(int i=0;i<26;i++){ next[L][i]=-1; num[L][i]=0;} 13 end[L++]=0; 14 return L-1; 15 } 16 void init(){ 17 L=0; root=newnode(); 18 } 19 20 void insert(char buf[]){ 21 int len=strlen(buf); 22 int now = root; 23 for(int i=0;i<len;i++){ 24 if(next[now][buf[i]-‘a‘]==-1){ 25 next[now][buf[i]-‘a‘]=newnode(); 26 27 } 28 now=next[now][buf[i]-‘a‘]; 29 } 30 end[now]++; 31 } 32 33 void build(){ 34 queue<int> Q; 35 fail[root]=root; 36 for(int i=0;i<26;i++){ 37 if(next[root][i]==-1) next[root][i]=root; 38 else{ 39 fail[next[root][i]]=root; 40 Q.push(next[root][i]); 41 } 42 } 43 while(!Q.empty()){ 44 int now=Q.front(); 45 Q.pop(); 46 for(int i=0;i<26;i++){ 47 if(next[now][i]==-1) next[now][i]=next[fail[now]][i]; 48 else{ 49 fail[next[now][i]]=next[fail[now]][i]; 50 Q.push(next[now][i]); 51 } 52 } 53 } 54 } 55 56 void print(char buf[]){ 57 int len=strlen(buf); 58 int now=root; 59 for(int i=0;i<=len;i++){ 60 printf("%d",i); 61 for(int j=0;j<26;j++) printf(" %d",next[now][j]); 62 printf("\n"); 63 now=next[now][buf[i]-‘a‘]; 64 } 65 } 66 }; 67 68 Trie ac; 69 char s[MAX]; 70 71 int main() 72 { 73 //freopen("data.txt","r",stdin); 74 while(scanf("%s",s),strcmp(s,"0")){ 75 ac.init(); 76 ac.insert(s); 77 ac.build(); 78 ac.print(s);//printf("\n"); 79 } 80 return 0; 81 }
HDU - 3407 - String-Matching Automata
标签:des style blog http color os io java strong
原文地址:http://www.cnblogs.com/sineatos/p/3946734.html