题目地址:https://www.spoj.com/problems/PHONELST/
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:
- Emergency 911
- Alice 97625999
- Bob 91125426
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.
Example
Input:
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346
Output:
NO
YES
题目大意:给你一组电话号码,判断是否存在一个电话号码是另一个电话号码的前缀。
一些废话:方法有多种,不同的时间复杂度要求下可选择不同的算法,我在hiho coder中遇到类似的题时选择的是用map存前缀(参见我的另一篇博客),当时懒,没有自己实现Trie树,但是事实证明出来混还是不能懒的,Spoj上的题复杂度要求是极高的,就比如这道题,Time limit: 0.177s-0.532s
,好吧我还是建树吧。
思 路:Trie树的基本思想就是将每个字符串转换为树中的一条路径。假设我们已经把输入的号码全都转换为了路径,对于一个新的号码,我们顺着树一步步走即可,如果遇到了没有出现的分支则新建。如果有前缀则会出现以下两种情况:
- 顺着树一直走,走到新号码的末尾也没有新建一个节点,说明自己成了别的号码的前缀
- 顺着树一直走,走着走着发现走到了别的号码的末尾,说明别的号码成了自己的前缀。
这棵树是一棵多叉树,由于本题是电话号码,所以字符串中只包含数字,这样每个节点只需用next[10]来存储自己的子节点。
基于以上就可以ac了。
#include <bits/stdc++.h>
using namespace std;
typedef struct node{
int type; // -1表示叶节点
node* next[10];
node(){
for(int i = 0;i < 10; i++)
next[i] = NULL;
}
}node;
void dfs(node* root){
if(root == NULL)
return ;
else{
for(int i = 0;i < 10; i++){
if(root->next[i] != NULL){
cout << i << endl;
dfs(root->next[i]);
}
}
}
delete root;
}
int main(int argc, char const *argv[])
{
int N,n;
cin >> N;
while(N--){
cin >> n;
int yes = 1;
vector<string> v(n);
for(int i = 0;i < n; i++)
cin >> v[i];
node* root = new node();
node* curr;
for(int i = 0;i < v.size(); i++){
curr = root;
for(int j = 0;j < v[i].size(); j++){
if(curr->next[v[i][j]-'0'] == NULL){ // 新建分支
curr->next[v[i][j]-'0'] = new node();
curr = curr->next[v[i][j]-'0'];
if(j == v[i].size()-1) // 到了号码末尾, 标记为叶节点
curr->type = -1;
}
else{
// 情况1:走到了自己的末尾也没有新建(若新建则不会再走上这条路,而是走上面if)
// 情况2:走到了别的号码的末尾
if(j == v[i].size()-1 || curr->next[v[i][j]-'0']->type == -1){
yes = 0;
break;
}
else
curr = curr->next[v[i][j]-'0'];
}
if(yes == 0)
break;
}
}
if(yes == 1)
cout << "YES" << endl;
else
cout << "NO" << endl;
// 测试用
// cout << "dfs " << endl;
// dfs(root);
}
return 0;
}