http://acm.hdu.edu.cn/showproblem.php?pid=1247
1 #include <iostream> 2 #include <stdio.h> 3 using namespace std; 4 #define maxn 50 5 char a[50005][60]; 6 struct Node{ 7 int flag; 8 Node *next[maxn]; 9 Node(){ 10 flag=0; 11 for(int i=0; i<maxn; i++) 12 next[i]=NULL; 13 } 14 } N; 15 16 void add(char x[]){ 17 Node *p=&N; 18 for(int i=0; x[i]; i++){ 19 int xx=x[i]-'a'; 20 if(p->next[xx]==NULL) 21 p->next[xx]=new Node; 22 p=p->next[xx]; 23 } 24 p->flag=1; 25 } 26 27 int findn(char x[]){ 28 Node *q=&N; 29 for(int i=0; x[i]; i++){ 30 int xx=x[i]-'a'; 31 if(q->next[xx]){ 32 q=q->next[xx]; 33 if(q->flag){ 34 int ff=1; 35 Node *t=&N; 36 for(int j=i+1; x[j]; j++){ 37 int yy=x[j]-'a'; 38 if(t->next[yy]) 39 t=t->next[yy]; 40 else{ 41 ff=0; 42 break; 43 } 44 } 45 if(ff){ 46 if(t->flag) 47 return 1; 48 } 49 } 50 } 51 } 52 return 0; 53 } 54 55 int main(){ 56 int n=0; 57 while(~scanf("%s",a[n])){ 58 add(a[n]); 59 n++; 60 } 61 for(int i=0; i<n; i++){ 62 if(findn(a[i])) 63 printf("%s ",a[i]); 64 } 65 return 0; 66 }
看心情更新,啦啦啦啦啦啦~~~~
1 #include <iostream> 2 #include <string.h> 3 #include <stdio.h> 4 using namespace std; 5 const int maxn = 50010; 6 char str[maxn][50]; 7 int n = 0, num = 1, m = 0, tree[maxn*4][30], flag[maxn*4]; 8 void add(){ 9 int node = 0; 10 for(int i = 0; str[n][i]; i++){ 11 int xx = str[n][i] - 'a'; 12 if(!tree[node][xx]) tree[node][xx] = num++; 13 node = tree[node][xx]; 14 } 15 flag[node] = 1; 16 } 17 bool query(){ 18 int node = 0, len = strlen(str[m]); 19 for(int i = 0; str[m][i]; i++){ 20 int xx = str[m][i] -'a'; 21 node = tree[node][xx]; 22 if(flag[node]){ 23 int node2 = 0, j; 24 for(j = i+1; str[m][j]; j++){ 25 int xxx = str[m][j] -'a'; 26 if(!tree[node2][xxx]) break; 27 node2 = tree[node2][xxx]; 28 } 29 if(j == len && flag[node2]) return true; 30 } 31 } 32 return false; 33 } 34 int main(){ 35 while(~scanf("%s", str[n])){ 36 add(), n++; 37 } 38 while(n--){ 39 if(query()){ 40 printf("%s ", str[m]); 41 } 42 m++; 43 } 44 return 0; 45 }
------------------------------------------------------------------------
http://acm.hdu.edu.cn/showproblem.php?pid=1277
将关键字建立字典树
1 #include <iostream> 2 using namespace std; 3 int n, m, cnt = 0; 4 char str[60009], ss[69]; 5 int vis[700000], sum[700000][26]; 6 bool mark[700000], flag = false; 7 void in(int x){ 8 int root = 0; 9 for(int i = 0; ss[i]; ++i){ 10 int xx = ss[i]-'0'; 11 if(!sum[root][xx]) sum[root][xx] = cnt++; 12 root = sum[root][xx]; 13 } 14 vis[root] = x; 15 } 16 void f(int x){ 17 int root = 0; 18 for(int i = x; str[i] != '