POJ 3630 --Trie

来源:互联网 发布:qq的网络传输协议 编辑:程序博客网 时间:2024/05/19 12:37
Phone List
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 23257 Accepted: 7153

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 withn, the number of phone numbers, on a separate line, 1 ≤ n ≤ 10000. Then followsn 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

Source

Nordic 2007

 

 

判断是否有字符串是其他字符串的前缀。

用法trie组织所有字符串,在插入时判断是否当前串是已插入串的前缀,或者已插入串是当前插入串的前缀。

 

 

 

#include <iostream>#include <stdio.h>#include <cstring>using namespace std;const int PHON_LNG = 10 + 2,MAX_SIZE = 10000 * (10 + 2) + 5,NUMS = 10 + 2;int num[MAX_SIZE][NUMS],val[MAX_SIZE],flag;int size;int idx(char c){   return c - '0';}void init_trie(int n){    size = 1;    memset(val, 0, sizeof(int) * (n + 5) * (10 + 2));    memset(num[0], 0, sizeof(num[0]));}void insert(char *str){    int cur = 0, c;    for(int i = 0; str[i]; ++i)    {        c = idx(str[i]);        if(!num[cur][c])        {            num[cur][c] = size;            memset(num[size], 0, sizeof(num[0]));            val[size] = 0;            size++;        }        cur = num[cur][c];        if(val[cur])        {            flag = 1;            break;        }    }    val[cur] = 1;    for(int i = 0; i <= 9; i++)    if(num[cur][i])    {        flag = 1;        break;    }}int main(){    int t,n;    char tmp[PHON_LNG];    scanf("%d",&t);    while(t--)    {        scanf("%d",&n);        flag = 0;        init_trie(n);        while(n--)        {            scanf("%s",tmp);            if(!flag)            {                insert(tmp);                if(flag)puts("NO");            }        }        if(!flag)puts("YES");    }   // cout << "Hello world!" << endl;    return 0;}


 

0 0