数组形式的 字典树   指针版本

#include<iostream>
#include<string.h>
#include<string>
#include<algorithm>
using namespace std;
int tot=0;
struct node
{
    int next[2];
    int tf;
}a[1000005];
int root=0 ;
int buildtrie(string ss)
{
    int p=root;
    int l=ss.size();
    int t=0;
    int x=0;
    for(int i=0;i<l;i++)
    {
        if(a[p].next[ss[i]-'0']==0)
        {
             a[p].next[ss[i]-'0']=++tot;
             a[tot].next[0]=0;
             a[tot].next[1]=0;
             a[tot].tf=0;
        }
        else t++;
        p=a[p].next[ss[i]-'0'];
        if(a[p].tf==1) x=1;

        //cout<<p<<"   "<<tot<<endl;
    }
    a[p].tf=1;
    if(x==1) return 1;
    if(t==l) return 1;
    else return 0;
}

char ss[100005];
int main()
{
    int k=0;
    int c=0;

    while(cin>>ss)
    {
       //cout<<ss<<endl;
        if(!strcmp(ss,"9"))
        {
           // cout<<"=="<<endl;
            k++;
            if(c==0) cout<<"Set "<<k<<" is immediately decodable"<<endl;
            else     cout<<"Set "<<k<<" is not immediately decodable"<<endl;
            c=0;
            //tot=0;
            a[root].next[0]=0; a[root].next[1]=0;
        }
        else
        {
            if(c==1) continue;
            if(buildtrie(ss)==1) c=1;
        }
    }
}
#include<iostream>
#include<string.h>
#include<string>
#include<algorithm>
using namespace std;
struct node
{
    node *next[2];
    int tf;
    node()
    {
        tf=0;
        memset(next,0,sizeof(next));
    }
};
node root;
int buildtrie(string ss)
{
    node *p=&root;
    int l=ss.size();
    int t=0;
    int x=0;
    for(int i=0;i<l;i++)
    {
        if(p->next[ss[i]-'0']==NULL)
        {
             p->next[ss[i]-'0']=new node;

        }
        else t++;
        p=p->next[ss[i]-'0'];
        if(p->tf==1) x=1;
    }
    p->tf=1;
    if(x==1) return 1;
    if(t==l) return 1;
    else     return 0;
}
char ss[10005];
int main()
{
    int k=0;
    int c=0;

    while(cin>>ss)
    {
        if(!strcmp(ss,"9"))
        {
            k++;
            if(c==0) cout<<"Set "<<k<<" is immediately decodable"<<endl;
            else     cout<<"Set "<<k<<" is not immediately decodable"<<endl;
            c=0;
            root.next[0]=NULL;
            root.next[1]=NULL;
        }
        else
        {
            if(c==1) continue;
            if(buildtrie(ss)==1) c=1;
        }
      //  cout<<c<<endl;
    }
}
原文地址:https://www.cnblogs.com/Andromeda-Galaxy/p/9741593.html