您的位置:首页 > 其它

hdu1671 Phone List

2016-02-05 12:10 405 查看
Problem 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:

1. Emergency 911

2. Alice 97 625 999

3. 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



题意:给你一些号码,问是否存在其中一个号码是另一个号码的前缀。
思路:可以构建一棵trie树,如果x是y的前缀,那么有两种情况,一种是x先于y出现,那么y在插入trie树的过程中一定会经过x的尾节点,另一种是y先于x出现,那么y的尾节点插入trie树后,会发现其后面还有节点,即ch[u][i](i>=0 && i<=9)中的其中一个不为0。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
typedef long long ll;
#define inf 99999999
#define pi acos(-1.0)
#define maxnode 1000000
int flag;
int ch[maxnode][11];
int val[maxnode];
int sz;
void init(){
    sz=0;memset(ch[0],0,sizeof(ch[0]));
}
int idx(char c){
    return c-'0';
}

void charu(char *s){
    int u=0,len=strlen(s),i,c;
    for(i=0;i<len;i++){
        c=idx(s[i]);
        if(!ch[u][c]){
            sz++;
            memset(ch[sz],0,sizeof(ch[sz]));
            val[sz]=0;
            ch[u][c]=sz;
            u=ch[u][c];
        }
        else{
            if(val[ch[u][c] ]){
                flag=0;break;
            }
            u=ch[u][c];
        }
    }
    val[u ]=1;
    for(i=0;i<=9;i++){
        if(ch[u][i]){
            flag=0;break;
        }
    }
}
int main()
{
    int n,m,i,j,T;
    char s[20];
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        flag=1;
        init();
        for(i=1;i<=n;i++){
            scanf("%s",s);
            if(flag){
                charu(s);
            }
        }
        if(flag==0)printf("NO\n");
        else printf("YES\n");
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: