hdu 1671 trie

#include <iostream>  ///AC
#include <cstdio>
#include <cstring>
#include <stdlib.h>
#define MAX 10
using namespace std;

struct trie{
   int k;
   trie *next[MAX];
};

trie *root;

void create(char *word)
{
    trie *p=root,*q;
    int m=strlen(word),i;
    for(i=0;i<m;i++)
    {
        int m1=word[i]-'0';
        if(p->next[m1]==NULL){
            q=(trie*) malloc( sizeof(trie) );
            q->k=1;
            for(int j=0;j<MAX;j++)
                q->next[j]=NULL;
            p->next[m1] = q ;
            p=q;
        }
        else{
            (p->next[m1])->k++;
            p=p->next[m1];
        }
    }
}

int find_(char *word)
{
    trie *p=root;
    int i,m=strlen(word);
    for(i=0;i<m;i++){
        int m1=word[i]-'0';
        p=p->next[m1];
    }
    if(p->k==1) return 1;   
    return 0;
}

void de_(trie *a)  ///  AC   两种释放内存均可
{
    if(a==NULL) return ;
    for(int i=0;i<MAX;i++)
       de_(a->next[i]);
    free(a);
}

void de(trie *a) /// AC
{
    int i;
    for(i=0;i<MAX;i++)
        if(a->next[i])
            de(a->next[i]);
    free(a);
}

int main()
{
    int T,n,i;
    char a[10010][11];
    scanf("%d",&T);
    while(T--)
    {
        root=(trie*)malloc(sizeof(trie));
        for(int j=0;j<MAX;j++)
                root->next[j]=NULL;
        root->k=0;
        scanf("%d",&n);
        for(i=0;i<n;i++)
        {
            scanf("%s",a[i]);
            create(a[i]);
        }
        int f=0;
        for(i=0;i<n;i++)
        {
            if(find_(a[i])==0)
                {  f=1;  break;  }
        }
        if(f==0) cout<<"YES"<<endl;
        else cout<<"NO"<<endl;
        de_(root);
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值