Hdu 1671 -Phone List (字典树模板)

题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1671

题目大意:
给出 n 个字符串,询问是否存在某个串完全为另一个串的前缀

分析:
将字符串按长度排序后插入即可,当前字符串插入字典树时,若中途发现该结点为单词,说明该单词的前缀已被插入,返回false,若全部能顺利插入则返回 true

注意:如果使用指针构造字典树,交G++可能会爆空间,建议交C++

代码:

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;

typedef long long ll;


struct Trie{
    Trie *next[10];
    int val;
    Trie(){
        val = 0;
        for (int i = 0 ; i < 10 ; i ++)
            next[i] = NULL;
    }
};

bool addword(char *str,Trie* node)
{

    if (node->val!=0)
        return false;
    if (node->next[str[0]-'0']==NULL)
        node->next[str[0]-'0'] = new Trie;
    node = node->next[str[0]-'0'];
    str++;
    //printf("%d\t",*str);
    if (*str)
        return addword(str,node);
    else
    {
        node->val++;
        return true;
    }
}

int query(char *str ,Trie *node)
{
   // printf("%d\t",*str);
    if (node->next[*str-'0']==NULL)
        return 0;
    else
        node= node->next[*str-'0'];
    ++str;
    if (*str)
        return query(str,node);
    else
        return node->val;
}

void del(Trie *node)
{
    for (int i = 0 ; i < 10 ; i ++)
    {
        if (node->next[i]!=NULL)
            del(node->next[i]);
    }
    delete node;
    node = NULL;
    return;
}
struct String{
    char str[20];
    int len;
    void read()
    {
        scanf("%s",str);
        len = strlen(str);
    }
    bool operator <(const String& a)
    {
        return len<a.len;
    }
}s[12000];


int main()
{
    int T,n;
    //printf("hello\n");
    Trie *head;
    //printf("world\n");
    scanf("%d",&T);

    while (T--)
    {

        scanf("%d",&n);
        head = new Trie;
        for (int i = 1;  i <= n ; i ++)
        {
            s[i].read();
        }
        sort(s+1,s+n+1);
        int f = 1;
        //printf("ok\n");
        for (int i = 1 ; i <= n ; i ++)
        {
            if (!addword(s[i].str,head))
            {
                f = 0;
                break;
            }
        }
        //printf("fuck\n");
        if (!f)
            printf("NO\n");
        else
            printf("YES\n");
        del(head);

    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值