HDU 1671 Phone List(

来源:互联网 发布:淘宝商品详情批量修改 编辑:程序博客网 时间:2024/05/18 00:02

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

题意:简单的说,判断是否有前缀出现,如果有输出NO如果没有输出YES。

思路:建树,最后记得要清空内存 不然MLE。

代码:

#include <stdio.h>#include <string.h>int t, n, judge, len;char str[105];struct Node {int vis;Node *next[10];Node() {for(int i = 0; i < 10; i ++)next[i] = NULL;vis = 0;}};int m;void Insert(Node *T) {if (m == len) {    for (int i = 0; i < 10; i ++)if (T->next[i] != NULL)    judge = 1;T->vis = 1;return;}int num = str[m] - '0';if (T->next[num] == NULL) {m ++;T->next[num] = new Node;Insert(T->next[num]);}else {m ++;if (T->next[num]->vis == 1)judge = 1;Insert(T->next[num]);}}void Delete(Node *T) {for (int i = 0; i < 10; i ++) {if (T->next[i] != NULL) {Delete(T->next[i]);}}delete T;}int main() {scanf("%d", &t);while (t --) {Node *T = new Node;judge = 0;scanf("%d", &n);while (n --) {m = 0;scanf("%s", str);len = strlen(str);Insert(T);}if (judge)printf("NO\n");elseprintf("YES\n");Delete(T);}return 0;}



原创粉丝点击