本文主要是介绍HDU 1671 Phone List(,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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.
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
题意:简单的说,判断是否有前缀出现,如果有输出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;
}
这篇关于HDU 1671 Phone List(的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!