F - Phone List HDU - 1671 (字典树查前缀)

本文介绍了一种用于判断电话号码是否为其他号码前缀的算法。通过构建Trie树结构,利用flag标记已出现的完整单词,sum记录以当前节点为前缀的单词数量,实现高效判断。代码示例使用C++实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给你一串电话号看是否有号码为其他号码的前缀。

分析:判断前缀我们只需要看前面字符串是否是已经出现字符串的前缀或者是后面的字符串的前缀。

(1)已经出现字符串的前缀我们。用flag代表是否出现以该节点结尾的单词;

(2)用sum代表以该节点结尾为前缀的单词数还有多少个,中间加判断条件即可。

#include<iostream>
#include<cstdio>
#include<map>
#include<string.h>
#include<cstring>
using namespace std;
const int maxn = 100010;
string a, b;
int trie[maxn][12], tot;
int m, rt, t, flag[maxn], ans, sum[maxn];


void insertit(int rt, string str)
{
    int len = str.size();
    for(int i = 0; i < len; i++)
    {
        int x = str[i] - '0';
        if(trie[rt][x] == 0) trie[rt][x] = ++tot;
        rt = trie[rt][x];
        if(flag[rt]) ans = 1;
        sum[rt]++;
    }
    if(sum[rt] > 1) ans = 1;
    flag[rt]++;
}

int main()
{
    scanf("%d", &t);
    while(t--)
    {
        rt = 1; tot = 1;
        scanf("%d", &m);
        ans = 0;
        while(m--)
        {
            cin >> a;
            insertit(rt, a);
        }
        if(ans) puts("NO");
        else puts("YES");
        memset(flag, 0 ,sizeof(flag));
        memset(trie, 0, sizeof(trie));
        memset(sum, 0, sizeof(sum));
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值