hdu1305 字典树

这题我开始想的简单了,WA一次,然后看disscuss里有人说输入时长度从小到大的,然后我信了。然后开始while(1) WA;然后我尝试先放如数组。后来对了;

discuss里面果然不能太相信。

根据出现的次数来判断是否为前缀。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct trie
{
    trie *next[2];
    int sum;
};
trie *root;
void creattrie()
{
    root=(trie*)malloc(sizeof(trie));
    for(int i=0;i<2;i++)
    {
        root->next[i]=NULL;
    }
    root->sum=0;
}
void insert(char *str)
{
    int i,j,cnt=0;
    int len=strlen(str);
    trie *p=root,*q;
    for(i=0;i<len;i++)
    {
        int id=str[i]-'0';
        if(p->next[id]==NULL)
        {
            q=(trie*)malloc(sizeof(trie));
            for(j=0;j<2;j++)
                q->next[j]=NULL;
            q->sum=0;
            p->next[id]=q;
        }
        p=p->next[id];
        p->sum++;
    }
}

int query(char *str)
{
    int i,j;
    int cnt=0;
    int len=strlen(str);
    trie *p=root;
    for(i=0;i<len;i++)
    {
        int id=str[i]-'0';
        p=p->next[id];
    }
    if(p->sum>1)//判断到该字符串结束时,现在的sum是否超过2,如果是,那就代表后面有以这个为前缀的词
        cnt=1;
    if(cnt)
        return 1;
    return 0;
}

int main()
{
    int i,j,flag,ff=0,ret,count;
    char str[100][30];
    while(gets(str[0])!=NULL)
    {
        if(str[0][0]=='9')break;
        count=1;
        creattrie();
        insert(str[0]);
        while(gets(str[count]))
        {
            if(str[count][0]=='9')break;
            insert(str[count]);
            count++;
        }
        flag=0;
        for(i=0;i<count;i++)
        {
            flag=query(str[i]);
            if(flag)break;
        }
        if(flag)printf("Set %d is not immediately decodable
",++ff);
        else printf("Set %d is immediately decodable
",++ff);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/sweat123/p/4688598.html