sdut oj 迷之好奇(字典樹)

Problem Description

FF得到了一個有n個數字的集合。不要問我爲什麼,有錢,任性。
FF很好奇的想知道,對於數字x,集合中有多少個數字可以在x前面添加任意數字得到。
如,x = 123,則在x前面添加數字可以得到4123,5123等。

Input

多組輸入。
對於每組數據
首先輸入n(1<= n <= 100000)。
接下來n行。每行一個數字y(1 <= y <= 100000)代表集合中的元素。
接下來一行輸入m(1 <= m <= 100000),代表有m次詢問。
接下來的m行。
每行一個正整數x(1 <= x <= 100000)。

Output

對於每組數據,輸出一個數字代表答案。

Sample Input

3
12345
66666
12356
3
45
12345
356

Sample Output

1
0
1

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct node
{
    int id;
    struct node *next[10];
    int f;
} NODE;

NODE T[1000000];
int top;

NODE *creat()
{
    NODE *p;
    int i;
    p = &T[top++];
    for(i=0; i<=9; i++)
    {
        p->next[i]=NULL;
    }
    p->id=0;
    p->f=0;
    return p;
}

void insertt(NODE *root,char s[])
{
    NODE *p=root;
    int i;
    for(i=0; s[i]!='\0'; i++)
    {
        int x=s[i]-'0';
        if(p->next[x]!=NULL)
        {
            p=p->next[x];
        }
        else
        {
            p->next[x]=creat();
            p=p->next[x];
        }
        p->id++;
    }
    p->f++;
}

int check(NODE *t,char s[])
{
    NODE *p=t;
    int i;
    for(i=0; s[i]!='\0'; i++)
    {
        int x=s[i]-'0';
        if(p->next[x]!=NULL)
        {
            p=p->next[x];
        }
        else
        {
            return 0;
        }
    }
    int k=p->id;
    if(p->f!=0)
        k-=p->f;
    return k;
}

int main()
{
    int i,j,n,m;
    char s[100010];
    char s1[100010];
    while(~scanf("%d",&n))
    {
        NODE *t;
        top=0;
        t=(NODE *)malloc(sizeof(NODE));
        t=creat();
        for(i=0; i<n; i++)
        {
            scanf("%s",s1);
            int len=strlen(s1);
            for(j=0; j<len; j++)
            {
                s[j]=s1[len-1-j];
            }
            s[len]='\0';
            insertt(t,s);
        }
        scanf("%d",&m);
        for(i=0; i<m; i++)
        {
            scanf("%s",s1);
            int len=strlen(s1);
            for(j=0; j<len; j++)
            {
                s[j]=s1[len-1-j];
            }
            s[len]='\0';
            int k=check(t,s);
            printf("%d\n",k);
        }
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章