【POJ3630】Phone List(字典树)

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;
}

转载于:https://www.cnblogs.com/gwj1314/p/10200115.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值