电话列表

# 题意
t个测试,每个测试中包含n个电话号码,在这些号码中如果存在一个号码是另一个号码的前缀,就称这些号码是不兼容的
兼容输出“YES”
不兼容输出“NO”

# 题解
1)即在trie插入中检查,若每个字符在trie 中已经存在,则当前插入的串是其他串的前缀
2)开一个数组记录每个串的结尾,如果插入过程中某个节点还有结尾标记,则该串中包含其他串为子串

 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 }

 

猜你喜欢

转载自www.cnblogs.com/hhyx/p/12528922.html