Poj-3630(字典樹,水題)
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
題意:
輸入:
t組輸入
每組一個n,代表下面的電話號碼數目
隨後n行,每行一個電話號碼
輸出:
有沒有一些號碼是另一個號碼的字首,有的話輸出NO,沒有就輸出YES
思路:
1.先把每個電話號碼當作一個字串構建字典樹,每個字串結尾的節點標記為1,代表這個節點對應的路徑有一個單詞
2.遍歷每個電話號碼,看這個號碼在字典樹的路徑上有沒有包括一個號碼,如果有的話直接輸出NO 都沒有的話就輸出YES
輸入中沒有重複的電話號碼
題中n的範圍是1e4,但是我開了1e5才過了
程式碼:
#include<iostream>
#include<string.h>
#include<string>
#include<stdio.h>
#include<cstdlib>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn=1010000;
struct Node
{
int cnt;
int net[10];
Node()
{
cnt=0;
clear();
}
void clear()
{
cnt=0;
memset(net,-1,sizeof(net));
}
} node[maxn];
int top;
void clear_tree(int n)
{
for(int i=n;~i;--i)
node[i].clear();
}
int hash_letter(char c)
{
return c-'0';
}
void insert_node(char *str)
{
int now=0;
while(*str)
{
if(node[now].net[hash_letter(*str)]==-1)
node[now].net[hash_letter(*str)]=++top;
now=node[now].net[hash_letter(*str)];
++str;
}
node[now].cnt=1;
}
int Solve(char *str)//
{
//根據str返回字首結束指標
int now=0;
while(*str)//根據當前節點和字元選擇該字元對應的節點
{
now=node[now].net[hash_letter(*str)];
++str;
if(node[now].cnt&&(*str!='\0'))
{
return 0;
}
}
return 1;
}
char words[10100][12];
int main()
{
int t,n,flag;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
clear_tree(top);
top=0;
for(int i=0;i<n;++i)
{
scanf("%s",words[i]);
insert_node(words[i]);
}
for(int i=0;i<n;++i)
{
flag=Solve(words[i]);
if(!flag)
break;
}
if(flag)
printf("YES\n");
else
printf("NO\n");
}
}