HDU 2846 字典树变形

来源:互联网 发布:微擎 ecshop 数据同步 编辑:程序博客网 时间:2024/05/02 02:00

Repository

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

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

大意:给定你一些商品的信息save(字符串),然后输入需要查询的字符串str,如果存在一个字符串save使得str是save的子串。之后输出多少个商品存在你所需要查询的字符串。

大体思路就是 建树的时候 要把该串的每个子串都加进去,这是要 多加个 标记 防止如 商品信息为abababab 而你查询的子串为 ab 这样一个商品会被多次计数。所以加个标记 表示商品的下标,这样就可以了,在标记不同时就计数并且更新序号、

AC:

#include <stdio.h>#include <algorithm>#include <iostream>#include <string.h>#include <string>using namespace std;typedef struct Trienode{    struct Trienode *nexts[26];    int id;    int cnt;}TrieNode,*Trie;Trie CreatNode(){    Trie p=new TrieNode;    memset(p->nexts,0,sizeof(p->nexts));    p->id=0;    p->cnt=0;    return p;}void Insertnode(Trie root,char *s,int num){    Trie p=root;    int id,i=0;    while(s[i])    {        id=s[i++]-'a';        if(p->nexts[id]==NULL)           {             p->nexts[id]=CreatNode();             ++(p->nexts[id]->cnt);             p->nexts[id]->id=num;           }        else        {            if(p->nexts[id]->id!=num)            {                ++(p->nexts[id]->cnt);                p->nexts[id]->id=num;            }        }        p=p->nexts[id];    }}int find(Trie root,char *s){    int id,i=0;    Trie p=root;    while(s[i])    {        id=s[i]-'a';        if(p->nexts[id]==NULL)            return 0;        p=p->nexts[id];        i++;    }    return p->cnt;}int main(){    int p,q;    while(~scanf("%d",&p))    {        Trie root=CreatNode();        char s[21];        int len;        for(int k=0;k<p;k++)        {            cin>>s;            len=strlen(s);            for(int i=0;i<len;i++)              {                Insertnode(root,s+i,k);              }        }        scanf("%d",&q);        while(q--)        {            cin>>s;            cout<<find(root,s)<<endl;        }    }    return 0;}
0 0
原创粉丝点击