题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2846
20 ad ae af ag ah ai aj ak al ads add ade adf adg adh adi adj adk adl aes 5 b a d ad s
0 20 11 11 2
代码如下:
#include <cstdio> #include <cstring> #include <malloc.h> #include <iostream> using namespace std; #define MAXN 26 typedef struct Trie { int IDD;//最后一次经过此结点的商品ID int v;//根据需要变化 Trie *next[MAXN]; //next是表示每层有多少种类的数,如果只是小写字母,则26即可, //若改为大小写字母,则是52,若再加上数字,则是62了 } Trie; Trie *root; void createTrie(char *str, int IDD) { int len = strlen(str); Trie *p = root, *q; for(int i = 0; i < len; i++) { int id = str[i]-'a'; if(p->next[id] == NULL) { q = (Trie *)malloc(sizeof(Trie)); // q->v = 1;//初始v==1 q->v = 0; for(int j = 0; j < MAXN; j++) q->next[j] = NULL; q->IDD = -1; p->next[id] = q; // p = p->next[id]; } /* else { p->next[id]->v++; p = p->next[id]; }*/ p = p->next[id]; if(p->IDD != IDD) { p->IDD = IDD; p->v++; } } } int findTrie(char *str) { int len = strlen(str); Trie *p = root; for(int i = 0; i < len; i++) { int id = str[i]-'a'; p = p->next[id]; if(p == NULL) //若为空集,表示不存以此为前缀的串 return 0; } return p->v; } int main() { int n, m; char str[MAXN]; root = (Trie *)malloc(sizeof(Trie)); for(int i = 0; i < MAXN; i++) root->next[i] = NULL; root->v=0; root->IDD=-1; scanf("%d",&n); for(int i = 0; i < n; i++) { scanf("%s",str); for(int j = 0; j < strlen(str); j++) //将字符串X=X1X2...Xn的分别以X1,X2...Xn开头的后缀字符串插入到Trie树中 { createTrie(str+j,i); } } scanf("%d",&m); for(int i = 0; i < m; i++) { scanf("%s",str); printf("%d\n",findTrie(str)); } return 0; }
原文地址:http://blog.csdn.net/u012860063/article/details/39034553