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:
1. Emergency 911
2. Alice 97 625 999
3. 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.
1. Emergency 911
2. Alice 97 625 999
3. 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.
InputThe 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.OutputFor 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
这个题目注意下要释放内存,同时他不是按顺序的。在后面也会出现有前面单词前缀的单词。
借这个题目贴下字典树的模板把
#include<iostream> #include<string> #include<vector> #include<sstream> #include<algorithm> using namespace std; typedef long long ll; struct Tire{ int num; bool flag; Tire *next[10]; Tire() { num = 0; flag = false; for(int i=0;i<10;i++){ next[i] = NULL; } } }; Tire *tree; bool flag; //判断字典树中是否有单词是别人的前缀 ll ans = 0; //记录不同的单词总数 void Insert(string word){ //在字典树中插入word字符串 Tire* p = tree; for(int i=0;i<word.length();i++){ int t = word[i] - '0'; if( p -> next[t] == NULL ){ p -> next[t] = new Tire; } p = p -> next[t]; if( p -> flag ) { flag = false; } p -> num ++; } if( !p->flag ) { p -> flag = true; ans ++; } if( p -> flag ) { if( p -> num > 1 ) { flag = false; } } } int Find(string word){ //计算当前前缀出现次数 Tire* p = tree; for(int i=0;i<word.length();i++){ int t = word[i] - 'a'; if( p -> next[t] == NULL ) { return 0; } p = p -> next[t]; } return p -> num; } bool isLife(string word){//判断当前字符串在字典树中是否存在 Tire* p = tree; for(int i=0;i<word.length();i++){ int t = word[i] - 'a'; if( p -> next[t] == NULL ) { return false; } p = p -> next[t]; } if( p -> flag == true ){ return true; } return false; } int deal(Tire* T)//释放内存空间 { int i; for(i=0;i<=9;i++) { if(T->next[i]!=NULL) deal(T->next[i]); } free(T); return 0; } int main(){ int T; cin >> T; while( T -- ) { int n; cin >> n; flag = true; tree = new Tire; while( n -- ) { string s; cin >> s; Insert(s); } if( flag ) { cout << "YES" << endl; }else cout << "NO" << endl; deal(tree); } return 0; }