Phone List

# Meaning of the questions
t test, each test contains n telephone numbers, if there is a number of these numbers is a prefix of another number, and called these numbers are incompatible
compatible output "YES"
is not compatible output "NO "

# Explanations
1) that is inserted into the trie checked, if each character already present in the trie, the current string is inserted into the other string prefix
2) open at the end of each string is an array of records, if during insertion of a node there closing tag, the string comprises a substring of another string

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int N=1e5+10;
 4 int n;
 5 int trie[N][10],tot=1;
 6 bool rec[N];
 7 inline void init(){
 8     memset(trie,0,sizeof trie);
 9     memset(rec,0,sizeof rec);
10     tot=1;
11 }
12 inline bool insert(char *str){
13     bool flag=0;
14     bool has_find=0;
15     int p=1;
16     for(int i=0;str[i];i++){
17         int ch=str[i]-'0';
18         if(!trie[p][ch]){
19             trie[p][ch]=++tot;
20             flag=1;
21         }
22         p=trie[p][ch];
23         if(rec[p])
24             has_find=1;
25     }
26     rec[p]=1;
27 
28     return !has_find && flag;
29 }
30 int main(){
31     ios::sync_with_stdio(0);
32     cin.tie(0);
33     cout.tie(0);
34     int t;
35     cin>>t;
36     while(t--){
37         cin>>n;
38         init();
39 
40         bool ans=1;
41         char str[20];
42         for(int i=0;i<n;i++){
43             cin>>str;
44             if(!insert(str))
45                 ans=0;
46         }
47         if(ans)
48             cout<<"YES"<<endl;
49         else
50             cout<<"NO"<<endl;
51     }
52     return 0;
53 }

 

 

Guess you like

Origin www.cnblogs.com/hhyx/p/12528922.html