POJ 3630 Phone List

4 篇文章 0 订阅
2 篇文章 0 订阅

POJ3630 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


题意很简单,就是说啊在一大堆电话中找到是否存在至少一个电话号码是别的号码的前缀。
按理说应该是用Trie树做,但是不知道怎么搞的我没用好,一直TLE.
后来又听说这道题还有更巧妙的方法,在我和Mr张两人的脑洞大开的各种尝试之后,搞了好久,终于把这道小破题搞定了~

Analyse:

为什么一定要用Trie树呢?—— 一眼题啊
为什么一定要用字符串处理呢,它是”电话号码“啊? ——。。。
是吗??
最简洁的想法:
首先把所有号码按照字典序排序,一定要用字典序,不能直接用大小比较,然后strcmp有个很神奇的功能,就是直接用字典序进行大小比较。所以我的下一个想法就是再倒回字符串。
为什么那么麻烦,直接字符串读入就好了嘛!!
所以,下一个问题就是 字符串 能/怎么 用sort排序啊。。
记得一个伟大的圣人曾经说过,结构体是万能的,我们可以用一个小小的node 然后,搞搞就出来了
Code:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#define MAXN 500000
using namespace std;
struct node
{
    char s[50];
}a[MAXN];
int t,n,flag;
int cmp(node a,node b)
{
    return (strcmp(a.s,b.s))<= 0 ?  1 : 0 ;
}
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        flag=0;
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%s",a[i].s);
        }
        sort(a+1,a+1+n,cmp);
        for(int i=1;i<=n-1;i++)
        {
            if(strstr(a[i+1].s,a[i].s)-a[i+1].s==0)
            {
                printf("NO\n");
                flag=1;
                break;
            }
            else
            {
                continue;
            }
        }
        if(!flag)
            printf("YES\n");
    }
    return 0;
}

掌声~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值