题解
题意:给你几个字符串,问读取文本的时候,是否可以清晰辨别当前读取的字符串是哪个
签到题
字典树建树,判断有没有分支或者文本重复就行了
哦对了,听学长说,这题dfs会T?还好我用的bfs
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+10;
char s[20];
int n,m,k;
int tree[N][20],tot,ed[N*20];
void build(){
int root=1;
int len=strlen(s);
for (int i = 0; i < len; ++i) {
int now=s[i]-'0';
if(!tree[root][now]){
tree[root][now]=++tot;
}
root=tree[root][now];
}
ed[root]++;//文本结束位置 判重
}
queue<int>q;
bool bfs(){
while(!q.empty())q.pop();
q.push(1);//root
while(!q.empty()){
int rt=q.front();
q.pop();
if(ed[rt]>1)return false;//重复
for (int i = 0; i <=9; ++i) {
if(tree[rt][i]){
if(ed[rt])return false;//当前位置有文本 且是其他文本的前缀 无法清晰分辨
q.push(tree[rt][i]);
}
}
}
return true;
}
void init(){
tot=1;
memset(tree, 0, sizeof(tree));
memset(ed, 0, sizeof(ed));
}
int main(){
ios::sync_with_stdio(0);
int T;
cin>>T;
for (int cs = 1; cs <= T; ++cs) {
bool f;
cin>>n;
init();
for (int i = 1; i <= n; ++i) {
cin>>s;
build();
}
f=bfs();
if(f)printf("Case #%d: Yes\n",cs);
else printf("Case #%d: No\n",cs);
}
return 0;
}