The 2019 ICPC Asia Shanghai Regional Contest-B-Prefix Code

知识点:字典树。

题目链接:

https://ac.nowcoder.com/acm/contest/4370/B

题意:t组数据,n个数字,问是否满足不存在任何一个数字是其他数字的前缀。

题解:套用字典树一个一个插入字符串。若在插入过程中遇到如下两种情况,则存在其中一个是另一个的前缀。

1.遍历完整个字符串都没有创造新的节点,说明该字符串是之前某个串的字串。

2.遍历过程中遇到了某个字符串的终点,说明存在一个字符串是该字符串的前缀。

若都不存在,则满足条件。

AC代码:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=1e5+10;
 4 int tree[maxn][10];
 5 bool color[maxn];
 6 bool flag;
 7 int cnt=0;
 8 void ist(string s){
 9     if(!flag)return;
10     flag=false;
11     int root=0;
12     for(char c:s){
13         if(tree[root][c-'0']){
14             root=tree[root][c-'0'];
15             if(color[root])return;
16             continue;
17         }
18         flag=true;
19         root=tree[root][c-'0']=cnt++;
20     }
21     color[root]=true;
22 }
23 int main(){
24     int t;
25     cin>>t;
26     for(int cas=1;cas<=t;cas++){
27         cnt=1;
28         memset(tree,0,sizeof tree);
29         memset(color,false,sizeof color);
30         flag=true;
31         int n;
32         cin>>n;
33         while(n--){
34             string s;
35             cin>>s;
36             ist(s);
37         }
38         printf("Case #%d: %s\n",cas,flag?"Yes":"No");
39     }
40     return 0;
41 }

猜你喜欢

转载自www.cnblogs.com/charles1999/p/12335139.html