Repository
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2534 Accepted Submission(s): 988
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
解题思路:子串就是串的前缀的后缀或者后缀的前缀,将串的所有后缀加入到字典树中即可
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int ans,len;
typedef struct TrieNode
{
int c,id;
struct TrieNode *next[26];
TrieNode()
{
id=-1;
c=0;
memset(next,0,sizeof(next));
}
};
TrieNode *root=NULL;
void CreatTree(char s[],int num)
{
int i,len;
len=strlen(s);
TrieNode *p=root;
TrieNode *temp;
for(i=0;i<len;i++)
{
if(p->next[s[i]-'a']==NULL)
{
temp=new TrieNode;
p->next[s[i]-'a']=temp;
}
p=p->next[s[i]-'a'];
if(p->id!=num)
p->c++;
p->id=num;
}
}
void Search(char s[],int d)
{
int i,j;
TrieNode *p=root;
for(i=0;i<d;i++)
{
if(p->next[s[i]-'a'])
p=p->next[s[i]-'a'];
else
{
ans=0;
return;
}
}
ans=p->c;
}
void Delete(TrieNode *node)
{
int i;
for(i=0;i<26;i++)
{
if(node->next[i])
Delete(node->next[i]);
delete node->next[i];
node->next[i]=0;
}
}
int main()
{
int i,j,m,n,len;
char str[25],temp[25];
root=new TrieNode;
scanf("%d",&n);
memset(str,'\0',sizeof(str));
for(i=0;i<n;i++)
{
scanf("%s",&str);
len=strlen(str);
for(j=0;j<len;j++)
{
strncpy(temp,str+j,len-j);
temp[len-j]='\0';
CreatTree(temp,i);
}
memset(str,'\0',sizeof(str));
}
scanf("%d",&m);
for(i=0;i<m;i++)
{
ans=0;
scanf("%s",&str);
len=strlen(str);
Search(str,len);
printf("%d\n",ans);
}
Delete(root);
return 0;
}