算法竞赛进阶指南---0x18(Trie)Phone List

题面

在这里插入图片描述

题解

  1. 我们可以用字典树来查询串中是否出现前缀,对于每个字符串,我们先判断其是不是前面字符串的前缀,或者前面字符串是不是它的前缀,然后再插入即可
  1. 我们可以将每个字符串的结尾标记,那么每次query的时候,如果当前字符串在原字典树中全部出现,那么这个字符串就是某个字符串的前缀,如果当前字符串从根节点开始向下查询时有一个节点的cnt>0,说明当前这个字符串有前缀存在于字典树中。

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
const int N = 100010;

int t, n;
char s[10];
int tr[N][10], cnt[N], idx;

void insert(char str[]) {
    int p = 0;
    for (int i = 0; str[i]; i++) {
        int u = str[i] - '0';
        if (!tr[p][u]) tr[p][u] = ++idx;
        p = tr[p][u];
    }
    cnt[p]++;
}

bool query(char str[]) {
    int p = 0;
    for (int i = 0; str[i]; i++) {
        int u = str[i] - '0';
        if (!tr[p][u]) return false;
        p = tr[p][u];
        if (cnt[p] > 0) return true;
    }
    return true;
}


int main() {

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    cin >> t;
    while (t--) {
        idx = 0;
        memset(cnt, 0, sizeof cnt);
        memset(tr, 0, sizeof tr);

        cin >> n;
        bool flag = true;
        while (n--) {
            cin >> s;
            if (query(s)) flag = false;
            insert(s);
        }
        if (flag) cout << "YES" << endl;
        else cout << "NO" << endl;
    }

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值