POJ3630 Phone List

来源:互联网 发布:淘宝网店代理免费加盟 编辑:程序博客网 时间:2024/06/14 12:55

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

2391197625999911254265113123401234401234598346

Sample Output

NOYES



题目大意:
给出几组电话号码,在某一组号码中,如果存在某一号码为其他号码的前缀,则输出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;}


0 0
原创粉丝点击