Phone List
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3544 Accepted Submission(s): 1191
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
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346
Sample Output
NO
YES
题意:所给的号码里面不能是其他号码的前缀,如果不满足这个条件,输出NO,否则YES;
思路:这是一道字典树也就是Trie树的模板题,没有A的估计都是超内存的,这里要注意的是,如果是多组数据输入,那么每一组输入输出完,要把用过的指针都释放掉,这样就不会超内存了,多加一个释放指针的函数就行了,主要是看如何释放内存,我释放内存的方法有点类似dfs,从root开始,遍历child有没有不是NULL,有就递归一次,返回的时候把指针释放掉;,下面看代码;
#include<iostream>
#include<cstdio>
#include<map>
#include<cstring>
using namespace std;
struct Trie {
bool End;
Trie *child[12];
Trie () {
memset(child,0,sizeof(child));
End = false;
}
};
void insert_ (Trie *root, char *str) {
int tmp,len = strlen(str);
Trie *rt = root;
for (int i = 0; i < len; ++i) {
tmp = str[i]-'0';
if(rt->child[tmp] == NULL) {
rt->child[tmp] = new Trie();
}
rt = rt->child[tmp];
}
rt->End = true;
}
bool search_ (Trie *root, char *str) {
int tmp,len = strlen(str),cnt = 0;
Trie *rt = root;
for (int i = 0; i < len; ++i) {
tmp = str[i]-'0';
rt = rt->child[tmp];
if(rt->End && i != len-1) return false; // != len-1是为了排除掉最后末尾是END = true的情况
}
return true;
}
void refree (Trie *rt) {
for (int i = 0; i < 12; ++i) {
if(rt->child[i] != NULL) refree(rt->child[i]);
delete (rt->child[i]);
}
}
char num[10002][13];
int main(void)
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int t,n;
scanf("%d",&t);
while (t--) {
scanf("%d",&n);
Trie *root = new Trie();
memset(num,0,sizeof(num));
for (int i = 0; i < n; ++i) {
scanf(" %s",num[i]);
insert_ (root, num[i]);
}
bool ok = true;
for (int i = 0; i < n; ++i) {
if(!search_ (root, num[i])) { ok = false; break; }
}
if(ok) printf("YES\n");
else printf("NO\n");
refree(root);
delete (root);
}
return 0;
}