hdu----(2222)Keywords Search(trie树)

Keywords Search

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 35683    Accepted Submission(s): 11520

Problem Description
In the modern time, Search engine came into the life of everybody like Google, Baidu, etc.
Wiskey also wants to bring this feature to his image retrieval system.
Every
image have a long description, when users type some keywords to find
the image, the system will match the keywords with description of image
and show the image which the most keywords be matched.
To simplify
the problem, giving you a description of image, and some keywords, you
should tell me how many keywords will be match.
 
Input
First line will contain one integer means how many cases will follow by.
Each case will contain two integers N means the number of keywords and N keywords follow. (N <= 10000)
Each keyword will only contains characters 'a'-'z', and the length will be not longer than 50.
The last line is the description, and the length will be not longer than 1000000.
 
Output
Print how many keywords are contained in the description.
 
Sample Input
1
5
she
he
say
shr
her
yasherhs
 
Sample Output
3
 
Author
Wiskey
 
代码:
 
字典树
 /*hdu 2222 字典树*/
//#define LOCAL
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
struct Trie
{
struct Trie *next[];
int tail;
};
char str[];
char ss[];
void in_Trie(char *s,Trie *root)
{
Trie *cur=root,*newcur;
for(int i=;s[i]!='\0';i++)
{
if(cur->next[s[i]-'a']==NULL)
{
newcur=new Trie; //(Trie*)malloc(sizeof(sizeof(Trie)));
for(int j=;j<;j++)
newcur->next[j]=NULL;
newcur->tail=;
cur->next[s[i]-'a']=newcur;
}
cur=cur->next[s[i]-'a'];
}
cur->tail++;
}
int query(char *s,Trie *root)
{
int i=,cnt=;
Trie *cur;
for(int j=;s[j]!='\0';j++)
{
cur=root;
for(i=j;s[i]!='\0';i++){
if(cur->next[s[i]-'a']!=NULL){
cur=cur->next[s[i]-'a'];
cnt+=cur->tail;
cur->tail=; //只需求出第一次出现的
}
else break;
}
}
return cnt;
}
void dele(Trie *root)
{
for(int i= ; i< ; i++ )
if(root->next[i]!=NULL)
dele(root->next[i]);
// free(root);
delete root;
}
int main()
{
#ifdef LOCAL
freopen("test.in","r",stdin);
#endif
int t,i,n;
Trie *root;
scanf("%d",&t);
while(t--)
{
root = new Trie ;
for(int j=;j<;j++)
root->next[j]=NULL;
root->tail=;
scanf("%d",&n);
for(i=;i<n;i++){
scanf("%s",str);
in_Trie(str,root);
}
scanf("%s",ss);
printf("%d\n",query(ss,root));
dele(root);
}
return ;
}
上一篇:数字信号处理--FFT与蝶形算法


下一篇:企业Nginx+Keepalived双主架构案例实战