POJ 3630 Trie树

来源:互联网 发布:淘宝生意参谋网址手机 编辑:程序博客网 时间:2024/05/19 14:55
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;


#define N 101000
struct st{
    bool isLeaf;
    int next[10];
}trie[N];
int nodep;
int root;


int new_node()
{
    memset(trie[nodep].next,-1,sizeof(trie[nodep].next));
    trie[nodep].isLeaf = false;
    nodep++;
    return nodep-1;
}


void trie_init()
{
    nodep = 0;
    root = new_node();
}


bool trie_find_insert(char phone[])
{
    int node = root;
    bool new_branch = false;
    for(int i=0;phone[i];i++){
        int ki = phone[i]-'0';
        if(trie[node].next[ki]==-1){
            new_branch = true;
            trie[node].next[ki] = new_node(); 
        }
        node = trie[node].next[ki];
        if(trie[node].isLeaf)  return true;
    }
    trie[node].isLeaf = true;
    if(new_branch)   return false;
    else             return true;
}


int main()
{
    int t;   scanf("%d",&t);
    while(t--){
        int n;  scanf("%d",&n);  getchar();
        
        trie_init();
        
        bool found = false;    
        char phone[12];
        for(int i=0;i<n;i++){
            gets(phone);
            if(!found)  found = trie_find_insert(phone);
        }
        if(!found)      puts("YES");
        else            puts("NO");
    }
   // system("pause");
    return 0;
}