zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    TCP粘包的拆包处理
    字节序列化
    同步,异步,阻塞和非阻塞
    用Doxygen生成文档
    Visual Studio新建的源文件的默认编码
    Boost编程之获取可执行文件的当前路径
    特征点寻找的基础数据结构和函数
    寻找Harris、Shi-Tomasi和亚像素角点
    特征点的基本概念和如何找到它们
    工业相机与普通相机的差别
  • 原文地址:https://www.cnblogs.com/sweat123/p/4688598.html
Copyright © 2011-2022 走看看