hdu 1305 Immediate Decodability (字典树)

判断给出的二进制编码是否是哈弗曼编码

#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#include<map>
using namespace std;
typedef long long lld;
const int oo=0x3f3f3f3f;
const lld OO=1e18;
const int Mod=1000000007;
const int maxn=50000+5;
const int maxm=12;


struct Trie
{
    struct TrieNode
    {
        int nCount;
        TrieNode* child[2];
        TrieNode()
        {
            memset(child,NULL,sizeof child);
            nCount=0;
        }
    }*root;

    Trie()
    {
        root=new TrieNode();
    }

    void Insert(char str[])
    {
        TrieNode* p=root;
        for(int i=0,k;str[i];i++,p=p->child[k],p->nCount++)
        {
            k=str[i]-'0';
            if(!p->child[k])
                p->child[k]=new TrieNode();
        }
    }

    int Search(char str[])
    {
        TrieNode* p=root;
        for(int i=0,k;str[i];i++)
        {
            k=str[i]-'0';
            if(p->child[k])
                p=p->child[k];
            else
                return 0;
        }
        return p->nCount;
    }

    void Free(TrieNode* Root)
    {
        TrieNode* p=Root;
        for(int i=0;i<2;i++)
            if(p->child[i])
                Free(p->child[i]);
        delete p;
    }

    ~Trie()
    {
        Free(root);
    }

};

char List[10][12],word[12];
int main()
{
    int n=0,f=1,cas=0;
    while(scanf("%s",List[++n])!=EOF)
    {
        Trie tree;
        while(scanf("%s",List[++n])&&List[n][0]!='9');
        n--;
        tree.Insert(List[n]);
        for(int i=n-1;i>=1;i--)
        {
            if(tree.Search(List[i])>0)
            {
                f=0;
                break;
            }
            tree.Insert(List[i]);
        }
        if(f)
            printf("Set %d is immediately decodable\n",++cas);
        else
            printf("Set %d is not immediately decodable\n",++cas);

        f=1;
        n=0;
    }
    return 0;
}





你可能感兴趣的:(hdu 1305 Immediate Decodability (字典树))