Phone List POJ - 3630(字典树模板题)
題意
給定 n個長度不超過 10的數字串,問其中是否存在兩個數字串S,T ,使得 S是 T的前綴,多組數據。
題目
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
分析
用字典樹,第一個為空點**(++tot易錯)**連接第一個數(0~9),每出現一個新點,插入字典書中。我的代碼是在建樹過程中找到出現的前綴,并記錄。出現前綴有兩種情況:
- .本身為樹上某數字串的前綴,則在建樹過程中沒有出現新點。
- .樹上的某數字串為當前數字串的前綴,則建樹過程中,掃過數字串的末尾(可以用book數組標記數字串結尾)搞了兩天,終于弄懂了,相對還是容易的。
- 復雜度:O(nlogn+nlog2^{2}2n)
AC代碼
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; const int N=6e5+10; const int Z=50; int T,n,tot,ch[N][Z]; char s[Z]; bool bo[N]; bool insert(char *s) {int l=strlen(s);int u=1;bool flag=false;for(int i=0; i<l; i++){int c=s[i]-'0';if(!ch[u][c])ch[u][c]=++tot;else if(i==l-1)flag=true;u=ch[u][c];if(bo[u])flag=true;}bo[u]=true;return flag; } int main() {scanf("%d",&T);while(T--){scanf("%d",&n);tot=1;memset(ch,0,sizeof(ch));memset(bo,false,sizeof(bo));bool ans=false;for(int i=1; i<=n; i++){scanf("%s",s);if(insert(s))ans=true;}if(ans)printf("NO\n");else printf("YES\n");}return 0; }總結
以上是生活随笔為你收集整理的Phone List POJ - 3630(字典树模板题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 六神丸治疗早泄吗
- 下一篇: 整肠生饭前吃还是饭后吃