您的位置:首页 > 其它

HDU-1671

2015-06-19 21:46 232 查看

Phone List

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


[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
For each test case, output “YES” if the list is consistent, or “NO” otherwise.

[align=left]Sample Input[/align]

2

3

911

97625999

91125426

5

113

12340

123440

12345

98346

[align=left]Sample Output[/align]

NO
YES

Source
2008 “Insigma International Cup” Zhejiang Collegiate Programming Contest - Warm Up(3)

/**
题意:给出n个电话号码,要求是否存在有的号码是另外一个字符串的前缀
做法:Trie树  一直是RE 是把主函数的root = new node() 写成 p = new node()
然后 C++MLE 然后每次询问完删除树就OK
**/
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <cmath>
using namespace std;
char ch[10005][12];
struct node
{
int count;
node *next[10];
node()
{
count = 0;
for(int i=0;i<10;i++)
{
next[i] = NULL;
}
}
};
node *root = new node(),*p;
void insert(char *s)
{
p = root;
for(int i=0;i<strlen(s);i++)
{
int tt = s[i] -'0';
if(p->next[tt] == NULL) p->next[tt] = new node();
p = p->next[tt];
p->count++;
}
}
int find(char *c)
{
int i;
p = root;
int len = strlen(c);
for(i=0;i<len;i++)
{
int tt = c[i]-'0';
if(p->next[tt]->count== 1) break;
p = p->next[tt];
}
if(i == len) return 0;
else  return 1;
}
void freedom(node *pp)
{
for(int i=0;i<10;i++)
{
if(pp->next[i] != NULL)
freedom(pp->next[i]);
}
free(pp);
}
int main()
{
//   freopen("in.txt","r",stdin);
int T;
scanf("%d",&T);
while(T--)
{
root  = new node();
int n;
bool flag = true;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%s",ch[i]);
insert(ch[i]);
}
for(int i=0;i<n;i++)
{
if(find(ch[i]) == 0)
{
flag = false;
break;
}
}
if(!flag) printf("NO\n");
else printf("YES\n");
freedom(root);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: