标签:
传送门:HDU 2896
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 14348 Accepted Submission(s): 3690
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int ls=2e2+10, lt=1e4+10, MAX_N=1e5+10, MAX_M=510; 4 char s[ls], t[lt]; 5 int q[MAX_N], head, tail; 6 bool used[MAX_M]; 7 struct node{ 8 int id, pre, last, pos[128]; 9 void init(){ 10 id=last=0; 11 memset(pos, 0, sizeof(pos)); 12 } 13 }; 14 node trie[MAX_N]; 15 void get_line(char *s){ 16 char ch; 17 while((ch=getchar())==‘\n‘); 18 int i=0; 19 s[i++]=ch; 20 while((ch=getchar())!=‘\n‘&&ch!=EOF) s[i++]=ch; 21 s[i]=‘\0‘; 22 } 23 int build_trie(int N){ 24 int tot=0; 25 trie[tot].init(); 26 int now; 27 for(int id=1; id<=N; id++){ 28 get_line(s); 29 now=0; 30 for(int i=0; s[i]; i++){ 31 int &nt=trie[now].pos[s[i]]; 32 now=nt?nt:(trie[++tot].init(), nt=tot); 33 } 34 trie[now].id=id; 35 trie[now].last=now; 36 } 37 return tot; 38 } 39 void build_ac(){ 40 head=tail=0; 41 for(int i=0; i<128; i++){ 42 int &nt=trie[0].pos[i]; 43 if(nt){ 44 trie[nt].pre=0; 45 q[tail++]=nt; 46 } 47 } 48 int pre; 49 while(head!=tail){ 50 int &top=q[head++]; 51 for(int i=0; i<128; i++){ 52 pre=trie[top].pre; 53 int &nt=trie[top].pos[i]; 54 if(!nt) nt=trie[pre].pos[i]; 55 else{ 56 q[tail++]=nt; 57 while(!trie[pre].pos[i]&&pre) pre=trie[pre].pre; 58 pre=trie[nt].pre=trie[pre].pos[i]; 59 int &last=trie[nt].last; 60 last=last?last:trie[pre].last; 61 } 62 } 63 } 64 } 65 void get_ans(int last, int &cnt){ 66 while((last=trie[last].last)&&!used[trie[last].id]){ //error-prone 67 used[trie[last].id]=true, cnt++; 68 } 69 } 70 void match(int N, int V){ 71 int cnt, tot=0; 72 for(int w=1; w<=N; w++){ 73 get_line(t); 74 memset(used, 0, sizeof(used)); 75 cnt=0; 76 for(int i=0, pre=0; t[i]; i++){ 77 pre=trie[pre].pos[t[i]]; 78 get_ans(pre, cnt); 79 if(cnt>=3) break; 80 } 81 if(!cnt) continue; 82 tot++; 83 printf("web %d:", w); 84 for(int i=1; i<=V; i++) 85 if(used[i]) 86 printf(" %d", i); 87 puts(""); 88 } 89 printf("total: %d\n", tot); 90 } 91 int main(){ 92 freopen("in", "r", stdin); 93 int N, M; 94 scanf("%d", &N); 95 build_trie(N); 96 build_ac(); 97 scanf("%d", &M); 98 match(M, N); 99 return 0; 100 }
标签:
原文地址:http://www.cnblogs.com/Patt/p/4619473.html