hdu Phone List

来源:互联网 发布:淘宝老版本苹果版下载 编辑:程序博客网 时间:2024/05/17 21:52
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
--------------------------------------------------------------------------
这个字典树,要加上一个释放空间的deal函数,否则会超内存
#include<stdio.h>#include<string.h>#include<algorithm>#include<malloc.h>using namespace std;typedef struct tree{tree *next[10];int con;}Trie;Trie *root;void createTrie(char *str){Trie *p,*q;int len,i,j,id;q = root;len = strlen(str);for(i=0;i<len;i++){id = str[i] - '0';if(q->next[id]==NULL){p = (Trie*)malloc(sizeof(Trie));q->next[id] = p;q = q->next[id];q->con=1;for(j=0;j<10;j++)q->next[j]=NULL;}else{q = q->next[id];q->con++;}}//q->con=-1;}void deal(Trie *t)//释放内存{int i;if(t==NULL)return ;for(i=0;i<10;i++){if(t->next[i]!=NULL)//递归调用从叶节点开始释放deal(t->next[i]);}free(t);return ;}int find(char *str){int len,i,j,id;Trie *q;q = root;len = strlen(str);for(i=0;i<len;i++){id = str[i] - '0';if(q->next[id]==NULL)return 0;elseq = q->next[id];}return q->con;}int main(){char phone[10010][20];int t,n,k,flag,i;memset(phone,0,sizeof(phone));scanf("%d",&t);while(t--){root = (Trie*)malloc(sizeof(Trie));for(i=0;i<10;i++)root->next[i]=NULL;scanf("%d",&n);for(i=0;i<n;i++){scanf("%s",phone[i]);createTrie(phone[i]);}flag=1;for(i=0;i<n;i++){k = find(phone[i]);if(k!=1){flag=0;break;}}if(flag)printf("YES\n");elseprintf("NO\n");memset(phone,0,sizeof(phone));deal(root);}return 0;}
0 0
原创粉丝点击