hdu 2846Repository

来源:互联网 发布:linux vi 怎么查找 编辑:程序博客网 时间:2024/06/05 06:35

Repository

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 3413    Accepted Submission(s): 1283


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
20adaeafagahaiajakaladsaddadeadfadgadhadiadjadkadlaes5badads
 

Sample Output
02011112
 

Source
2009 Multi-University Training Contest 4 - Host by HDU
 

题目大意及思路:

就是查一个字符串出现的次数,假设有字符串addd,查d出现的次数,d出现次数是1而不是3,也就是说不管母串中出现了几个子串,子串只相当与出现1次;
用字典树做要做一个标记mark;

ac代码:

#include<iostream>#include<cstring>#include<cstdio>using namespace std;struct TrieNode{int data;int mark;       //做标记 TrieNode *next[26];TrieNode(){data=0;mark=-1;memset(next,0,sizeof(next));}}; TrieNode *root=NULL;void Build(char *c,int k){int i,v,l=strlen(c);TrieNode *p=root;TrieNode *q=NULL;for(i=0;i<l;i++){v=c[i]-'a';if(p->next[v]==NULL){q=new TrieNode;q->data=1;q->mark=k;p->next[v]=q;}p=p->next[v];if(p->mark!=k){p->mark=k;p->data++;    //如果不是同一个串的话,data自加1,否则不加,避免重复 }}} int Find(char *c){int i,v,l=strlen(c);TrieNode *p=root;for(i=0;i<l;i++){v=c[i]-'a';if(p->next[v]==NULL){return 0;break;}else p=p->next[v];}return p->data;}void Delate(TrieNode *root){for(int i=0;i<26;i++)if(root->next[i])Delate(root->next[i]);delete(root);}int main(){int Q,P,i,j;char c[21];root=new TrieNode;scanf("%d",&P);for(i=0;i<P;i++){scanf("%s",c);int l=strlen(c);for(j=0;j<l;j++)Build(c+j,i);      //插入字符串和字符串的序号,作为标记}scanf("%d",&Q);for(i=0;i<Q;i++){scanf("%s",c);printf("%d\n",Find(c));}Delate(root);return 0;}


0 0
原创粉丝点击