您的位置:首页 > 其它

好题 HDU 2846 Repository (字典树)

2015-06-09 19:47 288 查看
分析:给出一大堆的P,再输入一堆的Q,在P中找Q,输出有多少个。

要注意的是重复的,比如add中的d只能算一个。

2015 11 - 3 又重新刷了一次 还是没做出来,确实是很灵活,或者说自己太死板。

比如输入adc,首先会把adc插入到字典树中,然后 插入dc,最后c。

在比如 abcfg 顺序是 abcfg bcfg cfg fg g

能想到这个就很不错了,然后再判断是否有重复的。

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

int cnt;
const int MAX = 5000000;

struct trie
{
trie *next[26];
int v;
int flag;
void init()
{
v=0;
flag = -5;
memset(next,0,sizeof(next));
}
}heap[MAX];

inline trie *new_trie()
{
heap[cnt].init();
return &heap[cnt++];
}

inline void creat(char *s,int flag,trie *p)
{

for(;*s;s++)
{
int id = *s - 'a';
if(p->next[id] == NULL)
{
p->next[id] = new_trie();
}
p = p->next[id];
if(p->flag != flag)
{
p->flag = flag;
++(p->v);
}
}

}

inline int  find(char *s,trie *p)
{

for(;*s;s++)
{
int id = *s - 'a';
if(p->next[id] == NULL)
{
return 0;
}
p = p->next[id];
}
return p->v;
}

int main()
{
int k,i,m=0;
char s[25];
cnt = 0;

trie *root = new_trie();

cin>>k;
while(k--)
{
cin>>s;
int len = strlen(s);
for(i=0;i<len;i++)
{
creat(s+i,k,root);
}
}
cin>>k;
while(k--)
{
cin>>s;
cout<<find(s,root)<<endl;
}
return 0;
}



Repository

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)

Total Submission(s): 2853 Accepted Submission(s): 1091



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


Source

2009 Multi-University Training
Contest 4 - Host by HDU
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: