HDU1671 Phone List

来源:互联网 发布:中信期货交易软件 编辑:程序博客网 时间:2024/06/04 19:52

题目: 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

题意:
给出几组电话号码,判断是否有电话号码和某一条电话号码的前缀相同。如果相同输出NO,不同输出YES。

思路:链表版会超时。每次都动态创建内存,比较耗时间,当然可以考虑把链表存储起来。那么就直接考虑用静态数组。
但是需要注意的是用这个模板就要考虑到开数组的问题。因为每个电话号码最多有十位数字。每次测试数据最多有10000个电话号码。所以数组就要开到1e5。但是开到65000也可过。因为这题数据还不是很大。代码AC时间为 94毫秒,内存14400

#include<cstdio>#include<cstring>#include<memory.h>#include<algorithm>using namespace std;const unsigned short Max=65000;unsigned short letters;unsigned short node[Max][11];bool flag[Max];int getIndex(char a){    return a-'0';}bool put(char *s){    bool mark=false;    int index,len=strlen(s),next=0;    for(int i=0;i<len;i++){        index=getIndex(s[i]);        if(!node[next][index]){            mark=true;            flag[letters]=false;            node[next][index]=letters++;        }        next=node[next][index];        if(flag[next])return false;    }    flag[next]=true;    if(!mark)return false;    return true;}int main(){    int times,n;    char s[11];    scanf("%d",&times);    while(times--){        letters=1;        scanf("%d",&n);        bool b=true;        for(int i=0;i<n;i++){            scanf("%s",s);            if(b)                b=put(s);        }        if(b)            printf("YES\n");        else            printf("NO\n");        for(int i=0;i<letters;i++){            memset(node[i],0,sizeof(node[i]));        }    }    return 0;}
1 0