POJ 3630 Phone List

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;
}

掌聲~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章