poj 3630 Phone List

Posted 8023spz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj 3630 Phone List相关的知识,希望对你有一定的参考价值。

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

Source

 
字典树,插入的时候记得标记,如果是以某个数字结尾,就标记为2,其他经过的都标记为1,分为两种情况,a是b的前缀,先插入a,那么再插入b的时候发现到了a的结尾时,标记为2,如果先插入b,那么再插入a时,发现到了a的结尾时,标记为1,都是NO的情况。
代码:
#include <iostream>
#include <cstdio>
#include <sstream>
#include <cstring>
using namespace std;
int n,t,pos;
int trie[1000001][10];
int tail[1000001],flag;
void Insert(string s) {
    int i = 0,c = 0,len = s.size();
    while(i < len) {
        int d = s[i] - 0;
        if(!trie[c][d]) {
            trie[c][d] = ++ pos;
        }
        c = trie[c][d];
        if(tail[c] == 2 || i == len - 1 && tail[c])flag = 0;
        tail[c] = 1;
        i ++;
    }
    tail[c] = 2;
}
int main() {
    scanf("%d",&t);
    char s[51];
    for(int i = 1;i <= t;i ++) {
        memset(tail,0,sizeof(tail));
        flag = 1;
        scanf("%d",&n);
        for(int j = 0;j < n;j ++) {
            scanf("%s",s);
            Insert(s);
        }
        puts(flag ? "YES" : "NO");
    }
}

 

以上是关于poj 3630 Phone List的主要内容,如果未能解决你的问题,请参考以下文章

poj3630:Phone List——题解

POJ3630 Phone List

poj3630 Phone List (trie树模板题)

[POJ 3630] Phone List

POJ3630——Phone List(Trie)

Trie入门--Poj3630 Phone List