http://acm.hdu.edu.cn/showproblem.php?pid=2846
Problem Description When you go shopping, you can search in repository for avalible merchandises by the computers and internet. First you give the search system a name about something, then the system responds with the results. Now you are given a lot merchandise names in repository and some queries, and required to simulate the process.
Input There is only one case. First there is an integer P (1<=P<=10000)representing the number of the merchanidse names in the repository. The next P lines each contain a string (it's length isn't beyond 20,and all the letters are lowercase).Then there is an integer Q(1<=Q<=100000) representing the number of the queries. The next Q lines each contains a string(the same limitation as foregoing descriptions) as the searching condition.
Output For each query, you just output the number of the merchandises, whose names contain the search string as their substrings.
Sample Input 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
Sample Output 0 20 11 11 2 |
#include <cstdio>
#include <cstring>
#include <malloc.h>
#include <iostream>
using namespace std;
#define MAXN 26
typedef struct Trie
{
int ID;//最后一次经过此结点的商品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;//它以后的其他节点都先赋值为null
q->ID = -1;//新节点的id赋值为-1;
p->next[id] = q;//p的...赋值为q;
p = p->next[id];//转移一下位置;
}
else
{
// p->next[id]->v++;
p = p->next[id];//不为空的情况;
}
if(p->ID != IDD)//例如adadad只记录一次ad,防止多次记录情况;
{
p->ID = 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;
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
scanf("%s",str);
for(int j = 0; j < strlen(str); j++) //将字符串a=a1a2...an分别以a1,a2...an开头的字符串插入Trie树中
{
createTrie(str+j,i);
//cout<<str+j<<endl;
}
}
scanf("%d",&m);
for(int i = 0; i < m; i++)
{
scanf("%s",str);
printf("%d\n",findTrie(str));
}
return 0;
}