hdu1671 Phone List

来源:互联网 发布:深渊巨口皮肤淘宝 编辑:程序博客网 时间:2024/05/16 02:20

Phone List

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


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
2391197625999911254265113123401234401234598346
 

Sample Output
NOYES
 

AC代码

#include<iostream>using namespace std;struct node{    int flag;    node *next[10];    node()    {        flag=0;        memset(next,0,sizeof(next));    }};node *root=NULL;void build(char *s){    node *p=root;    int i,j;    for(i=0;s[i]!='\0';i++)    {        j=s[i]-'0';        if(p->next[j]==NULL)            p->next[j]=new node;          p=p->next[j];    }    p->flag=1;}int findstr(char *s){ node *p=root;    int i;    for(i=0;s[i]!='\0';i++)    {               if(p->next[s[i]-'0']!=NULL){p=p->next[s[i]-'0'];if(p->flag)return 0;}else            return 1;        } return 0;}void freedom(node *p){    for(int i=0; i<10; i++)    if(p->next[i]!= NULL)        freedom(p->next[i]);    free(p);}int main(){        int t,n,i,flag;char str[15];    scanf("%d",&t);    while(t--)    {   root=new node;          flag=1;        scanf("%d",&n);        for(i=0;i<n;i++)        {            scanf("%s",str);if(flag){flag=findstr(str);            build(str);}        }            if(flag)                printf("YES\n");            else                printf("NO\n");           freedom(root);    }         return 0;}

同样为字典树,不解释!

谢谢阅读!
原创粉丝点击