0
点赞
收藏
分享

微信扫一扫

【POJ3630】Phone List(字典树)

三千筱夜 2023-02-08 阅读 25


problem

  • 给定n个长度不超过10的数字串(n<10^4)
  • 问其中是否存在两个数组串a,b,满足a是b的前缀。存在输出NO,不存在输出YES

solution

  • 将所有数字串构建成字典树
  • 在插入过程中,如果没有新建任何节点(当前串是之前串的前缀))或者插入过程中经过某个带结尾标记的串(之前串是当前串的前缀),则存在前缀情况。

codes

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1e5+10;

int tire[maxn][26], val[maxn], tot;
void build(){
tot = 1;
memset(tire,0,sizeof(tire));
memset(val,0,sizeof(val));
}
bool insert(char *s){
bool jingguo = false, xinjian = false;
int len = strlen(s), u = 1;
for(int i = 0; i < len; i++){
int c = s[i]-'0';
if(tire[u][c]==0){
tire[u][c] = ++tot;
xinjian = true;
}
u = tire[u][c];
if(val[u])jingguo = true;
}
val[u] = 1;
if(!xinjian || jingguo)return true;
return false;
}

char s[20];
int main(){
int T;
scanf("%d",&T);
while(T--){
int n;
scanf("%d",&n);
build();
bool ans = false;
for(int i = 1; i <= n; i++){
scanf("%s",s);
if(insert(s))ans = true;//存在前缀
}
if(ans)cout<<"NO\n";
else cout<<"YES\n";
}
return 0;
}


举报

相关推荐

0 条评论