标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 34600 Accepted Submission(s): 13014
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <cmath> 6 using namespace std; 7 const int maxn = 5e5+5; 8 struct node 9 { 10 int next[30]; 11 int v; 12 }; 13 int sz = 1; 14 node tree[maxn]; 15 void init() 16 { 17 sz = 1; 18 memset(tree[0].next,0,sizeof(tree[0].next)); 19 tree[0].v = 0; 20 } 21 void build(char s[]) 22 { 23 int root = 0; 24 int n = strlen(s); 25 for(int i=0;i<n;i++) 26 { 27 int id = s[i]-‘a‘; 28 if(tree[root].next[id]==0) 29 { 30 memset(tree[sz].next,0,sizeof(tree[sz].next)); 31 tree[sz].v = 0; 32 tree[root].next[id] = sz++; 33 } 34 root = tree[root].next[id]; 35 tree[root].v += 1; 36 } 37 } 38 void match(char s[]) 39 { 40 int ans = 0,root = 0; 41 int n = strlen(s); 42 int flag = 0; 43 for(int i=0;i<n;i++) 44 { 45 int id = s[i]-‘a‘; 46 if(tree[root].next[id]) 47 { 48 root = tree[root].next[id]; 49 ans = tree[root].v; 50 } 51 else 52 { 53 flag = 1; 54 break; 55 } 56 } 57 if(!flag) printf("%d\n",ans); 58 else printf("0\n"); 59 } 60 int main() 61 { 62 init(); 63 char s[20]; 64 while(gets(s)&&s[0]!=‘\0‘) 65 { 66 build(s); 67 } 68 while(scanf("%s",s)!=EOF) 69 { 70 match(s); 71 } 72 return 0; 73 }
标签:
原文地址:http://www.cnblogs.com/littlepear/p/5819312.html