[hdu 1671] Phone List - Trie

本文介绍了一种使用Trie树的数据结构来解决电话号码列表中号码互为前缀的问题。通过构建Trie树并插入每个电话号码,算法能够有效判断列表是否一致——即不存在一个号码作为另一个号码的前缀。文章提供了完整的C++实现代码。
Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let’s say the phone catalogue listed these numbers: 
1. Emergency 911 
2. Alice 97 625 999 
3. Bob 91 12 54 26 
In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent. 

InputThe first line of input gives a single integer, 1 <= t <= 40, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 <= n <= 10000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.OutputFor each test case, output “YES” if the list is consistent, or “NO” otherwise.Sample Input

2
3
911
97625999
91125426
5
113
12340
123440
12345
98346

Sample Output

NO
YES

题意:判断某个字符串是全部字符串中的某个字符串的前缀,有输出YES, 反之NO
思路:利用Trie来做,可以变插入变检测,如果在插入过程中有标记节点,则之前某个字符串是该字符串的前缀,如果插入完成之后,其后有子数,则该字符串是某个字符串的前缀。
   每组Case做完后,要释放空间,再建立新树。
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;
#define Max 10
typedef struct TrieNode *Trie;
struct TrieNode
{
    Trie next[Max];
    int cnt;
    TrieNode()
    {
        for (int i = 0; i < Max; i++) {
            next[i] = NULL;
            cnt = 0;
        }
    }
};

bool Insert(Trie root, char *s)
{
    Trie p = root;
    for (int i = 0; s[i]; i++) {
        int t = s[i]-'0';
        if (p->next[t] == NULL)
            p->next[t] = new TrieNode;
        p = p->next[t];
        if (p->cnt >= 1) return 1;
    }
    p->cnt++;
    for (int i = 0; i < Max; i++) {
        if (p->next[i] != NULL)
            return 1;
    }
    return 0;
}

void FreeTrie(Trie root)
{
    for (int i = 0; i < Max; i++) {
        if (root->next[i] != NULL)
            FreeTrie(root->next[i]);
    }
    delete root;
}

int main()
{
    //freopen("1.txt", "r", stdin);
    int T;
    scanf("%d", &T);
    while (T--) {
        int n;
        char s[10010][20];
        scanf("%d", &n);
        Trie root = new TrieNode;
        int flag = 0;
        for (int i = 0; i < n; i++) {
            scanf("%s", s[i]);
            if (Insert(root, s[i]))
                flag = 1;
        }
        
        if (flag) printf("NO\n");
        else printf("YES\n");
        FreeTrie(root);
    }


    return 0;
}

 



转载于:https://www.cnblogs.com/whileskies/p/7273496.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值