杭電1671字典樹

Phone List

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8253    Accepted Submission(s): 2833


Problem Description
Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let’s say the phone catalogue listed these numbers:
1. Emergency 911
2. Alice 97 625 999
3. Bob 91 12 54 26
In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent.
 

Input
The first line of input gives a single integer, 1 <= t <= 40, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 <= n <= 10000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.
 

Output
For each test case, output “YES” if the list is consistent, or “NO” otherwise.
 

Sample Input
2 3 911 97625999 91125426 5 113 12340 123440 12345 98346
 

Sample Output
NO YES
 

Source

程序員 苦啊。。大年三十還要碼題,還好開始只是超了內存過了,不然這年還怎麼過。。
記得釋放內存就好了。。。


#include <cstdio>
#include <cstdlib>
#include <cstring>
struct node
{
    node * x[10];
    int end;
};
node *tree;
char stu[20];
int t,n,flag;
void create(node *&t)
{
    int i;
    t=(node*)malloc(sizeof(node));
    t->end=0;
    for(i=0;i<10;++i)
        t->x[i]=NULL;
}
void insertTree()
{
    node *f=tree;
    int i,j,len=strlen(stu);
    if(flag==0)
    {
  //      printf("stu  %s  len  %d\n",stu,strlen(stu));
   //     printf("if   flag %d\n",flag);
        for(i=0;i<len;++i)
        {
            int p=stu[i]-'0';
            if(f->x[p]==NULL)
            {
                f->x[p]=(node *)malloc(sizeof(node));
                f=f->x[p];
                f->end=0;
                for(j=0;j<10;++j)
                    f->x[j]=NULL;
                if(i==len-1)
                    f->end=1;
            }
            else
            {
                f=f->x[p];
                if(i==len-1||f->end==1)
                 {
                     flag=1;
                 }
            }
        }
    }
 //   printf("   ffff %d\n",flag);
}
void deleteTree(node *&t)
{
    int i;
   for(i=0;i<10;++i)
   {
       if(t->x[i]!=NULL)
       deleteTree(t->x[i]);
   }
   free(t);
}
int main()
{
    int i;
    scanf("%d",&t);getchar();
    while(t--)
    {
        flag=0;
        create(tree);
    //    printf("tree  %d\n",tree);
        scanf("%d",&n);
        for(i=1;i<=n;++i)
        {
            scanf("%s",stu);
            getchar();
            insertTree();
        }
        if(flag==1)
        {
            printf("NO\n");
        }
        else
        {
            printf("YES\n");
        }
        deleteTree(tree);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章