HDU2846(字典树变形)

Repository

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

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

如果有一个abcd串要把bcd cd d都加到树上,还有个问题就是重复的abab,所以加入子串的时候第一次abab,第二次bab第三次ab,这时候第三个串和第一个串前缀是一样的,这样cnt就不能增加,然后乱搞一下加个标记来处理刚才说到的问题。还有个奇葩的问题,HDU上一样的代码用G++交会爆内存然而C++就可以AC也是很迷。

#include "cstring"
#include "cstdio"
#include "cstring"
#include "string.h"
using namespace std;
typedef struct node
{
    node *next[26];
    int cnt;
    int mark;
    node()
    {
        cnt=0;
        memset(next,NULL,sizeof(next));
        mark=0;
    }
}node;
int len;
node *root=new node();
void ins(char s[],int mark)
{
    node *now=root;
    for(int start=0;start<len;start++)
    {
        now=root;
        for(int i=start;i<len;i++)
        {
            if(now->next[s[i]-'a']==NULL)
            {
                now->next[s[i]-'a']=new node();
                now=now->next[s[i]-'a'];
                now->mark=mark;
                now->cnt++;
            }
            else
            {
                now=now->next[s[i]-'a'];
                if(now->mark!=mark)
                {
                    now->cnt++;
                }
                now->mark=mark;
            }

        }
        if(now->mark!=mark)
        now->cnt++;
    }
    return;
}
int find(char pat[])
{
    node *now=root;
    for(int i=0;i<len;i++)
    {
        if(now->next[pat[i]-'a']==NULL)
            return 0;
        now=now->next[pat[i]-'a'];
    }
    return now->cnt;
}
int main()
{
    char s[25];
    int num;
    scanf("%d",&num);
    while(num--)
    {
        scanf("%s",s);
        len=strlen(s);
        ins(s,num+2);
    }
    scanf("%d",&num);
    while(num--)
    {
        scanf("%s",s);
        len=strlen(s);
        printf("%d\n",find(s));
    }
    return 0;
}

你可能感兴趣的:(HDU2846(字典树变形))