题目大意:给你n个字符串,然后给你m个子串,看这个子串在上面的多少个串中,出现过;
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2846
本题可以在字典树上进行改进;
AC代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cstdlib> 5 using namespace std; 6 const int maxn = 26; 7 typedef struct node 8 { 9 int count; 10 int id; 11 node *next[maxn]; 12 }trie; 13 void inser(trie *root,char *s,int id) 14 { 15 int i,index; 16 trie *p = root; 17 for(i =0 ;s[i];i++) 18 { 19 index = s[i]-'a'; 20 if(p->next[index] == NULL) 21 { 22 trie *temp= (trie *)malloc(sizeof(trie)); 23 for(int j=0;j<maxn;j++) 24 { 25 temp->next[j] = NULL; 26 } 27 temp->count = 0; 28 temp->id = -1; 29 p->next[index] = temp; 30 } 31 p=p->next[index]; 32 if(p->id != id) 33 { 34 p->id = id; 35 p->count++;//统计每个出现的个数; 36 } 37 } 38 } 39 int search(trie *root,char *s) 40 { 41 trie *p=root; 42 int i,index; 43 for(i=0;s[i];i++) 44 { 45 index = s[i]-'a'; 46 if(p->next[index] == NULL) return 0; 47 p=p->next[index]; 48 } 49 return p->count; 50 } 51 int main(int argc, char *argv[]) 52 { 53 int i,j; 54 int n,m; 55 char s[21]; 56 trie *root = (trie *)malloc(sizeof(trie));//清理内存,初始化; 57 for(i=0;i<maxn;i++) 58 { 59 root->next[i] = NULL; 60 } 61 root->count = 0; 62 root->id = -1; 63 root->count = 0; 64 root->id = -1; 65 scanf("%d",&n); 66 for(i =0;i<n;i++) 67 { 68 69 scanf("%s",s); 70 for(j =0;j<strlen(s);j++) 71 { 72 inser(root,s+j,i); 73 } 74 } 75 scanf("%d",&m); 76 for(i=0;i<m;i++) 77 { 78 scanf("%s",s); 79 printf("%d ",search(root,s)); 80 } 81 return 0; 82 }
代码二:
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<cstdlib> 5 using namespace std; 6 struct node 7 { 8 int count, id; 9 node *childs[26]; 10 node(){ 11 id=-1; 12 count=0; 13 int i; 14 for(i=0; i<26; i++) 15 childs[i]=NULL; 16 } 17 }; 18 node *root=new node; 19 node *current, *newnode; 20 void insert(char *str, int d) 21 { 22 int i, m; 23 current=root; 24 for(i=0; i<strlen(str); i++) 25 { 26 m=str[i]-'a'; 27 if(current->childs[m]!=NULL) 28 { 29 current=current->childs[m]; 30 } 31 else{ 32 newnode=new node; 33 current->childs[m]=newnode; 34 current=newnode; 35 } 36 if(current->id!=d) 37 { 38 current->id=d; 39 ++(current->count); 40 } 41 } 42 } 43 int search(char *str) 44 { 45 //printf("%s",str); 46 int i, m; 47 current=root; 48 for(i=0; i<strlen(str); i++) 49 { 50 m=str[i]-'a'; 51 if(current->childs[m]==NULL) 52 return 0; 53 current=current->childs[m]; 54 } 55 return current->count; 56 } 57 58 int main() 59 { 60 int i, t, s, k; 61 char a[26]; 62 scanf("%d",&t); 63 s=0; 64 while(t--){ 65 scanf("%s",a); 66 s++; 67 for(i=0; i<strlen(a); i++) 68 insert(a+i, s); 69 } 70 scanf("%d",&k); 71 while(k--){ 72 scanf("%s",a); 73 printf("%d ",search(a)); 74 } 75 return 0; 76 }