HDU1671 Phone List

題目: 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章