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:
- Emergency 911
- Alice 97 625 999
- 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树的应用 边插入边寻找
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <cmath>
#include <stack>
#include <string>
#include <map>
#include <set>
#define pi acos(-1.0)
#define LL long long
#define ULL unsigned long long
#define inf 0x3f3f3f3f
#define INF 1e18
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define debug(a) printf("---%d---\n", a)
#define mem0(a) memset(a, 0, sizeof(a))
#define memi(a) memset(a, inf, sizeof(a))
#define mem1(a) memset(a, -1, sizeof(a))
using namespace std;
typedef pair<int, int> P;
const double eps = 1e-10;
const int maxn = 1e6 + 5;
const int mod = 1e8;
struct Node
{
int flag;
Node* next[10];
}tree[maxn];
int node, ok;
Node* Creat()
{
Node* p = &tree[node++];
p->flag = 0;
for (int i = 0; i < 10; i++)
p->next[i] = NULL;
return p;
}
void Insert(Node* root, char* s) // 边插入边寻找
{
Node* p = root;
for (int i = 0; i < strlen(s); i++){
int k = s[i] - '0';
if (p->next[k] && i == strlen(s)-1){ // 这个判断之前是否有一个号码 它的前缀为当前号码
ok = 1;
return;
}
if (p->next[k]){
if (p->next[k]->flag){ // 这个判断之前是否有一个号码 他为当前号码的前缀
ok = 1;
return;
}
}
else p->next[k] = Creat();
p = p->next[k];
}
p->flag = 1;
}
int main(void)
{
// freopen("C:\\Users\\wave\\Desktop\\NULL.exe\\NULL\\in.txt","r", stdin);
int T, n, i;
char s[15];
scanf("%d", &T);
while (T--){
scanf("%d", &n);
node = ok = 0;
Node* root = Creat();
for (i = 1; i <= n; i++){
scanf("%s", &s);
if (!ok)
Insert(root, s);
}
if (ok) puts("NO");
else puts("YES");
}
return 0;
}
本文介绍了一种使用Trie树的数据结构来解决电话号码列表中号码互为前缀的问题。通过边插入边查找的方式,该算法能高效地判断给定的电话号码列表是否满足任意两个号码都不互为前缀的条件。
501

被折叠的 条评论
为什么被折叠?



