现在的位置: 首页 > 综合 > 正文

Phone List

2014年09月04日 ⁄ 综合 ⁄ 共 1906字 ⁄ 字号 评论关闭

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
/*算法分析:
法一:先排序必须是 n*logn 的复杂度,在比较相邻的两个字符串
是否互为前缀  比较时花的时间为 strlen(s);
时间复杂度为:10^5*log 10^5 *10 ,所以在1s内;
这个题起初用的是 sort()和STL 超时了 又改了STL还是超时了,
继续把sort()改了用 归并写的 发现 用string 会报错的
最后改用 char 终于险过了*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 100010
using namespace std;
char list[N][15];
char temp[N][15];
void merge(int s1,int e1,int s2,int e2)
{
    int i,j,k;
    i=s1;j=s2;k=0;
    while(i<=e1&&j<=e2)
    {
        if(strcmp(list[i],list[j])<0) strcpy(temp[k++],list[i++]);
        else strcpy(temp[k++],list[j++]);
    }
    while(i<=e1)  strcpy(temp[k++],list[i++]);
    while(j<=e2)  strcpy(temp[k++],list[j++]);
    for(k=0,i=s1;i<=e2;i++,k++)    strcpy(list[i],temp[k]);
}
void mergesort(int s,int e)
{
    int m=0;
    if(s<e)
    {
        m=(s+e)>>1;
        mergesort(s,m);
        mergesort(m+1,e);
        merge(s,m,m+1,e);
    }
}
bool judge(char *s1,char *s2)
{
    int i=0,j=0,len1,len2;
    len1=strlen(s1);len2=strlen(s2);
    while(i<len1&&j<len2)
    {
        if(s1[i]==s2[j])
        {
            i++;j++;
        }
        else  return false;
    }
    if(i==len1||j==len2) return true;
}
int main()
{
    int test;
    scanf("%d",&test);
    while(test--)
    {
        int n;
        scanf("%d",&n);
        int i;
        for(i=0;i<n;i++)
        {
            scanf("%s",list[i]);
        }
        mergesort(0,n-1);
        bool yes=true;
        for(i=0;i<=n-2;i++)
        {
            if(judge(list[i],list[i+1]))
            {
                yes=false;break;
            }
        }
        if(yes) printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}
 

Sample Output

NO YES

抱歉!评论已关闭.