HDU 1671——Trie树应用

看不懂可以先看看讲解http://blog.csdn.net/chuck001002004/article/details/50421065

HDU 1671:http://acm.hdu.edu.cn/showproblem.php?pid=1671

题意:给定一些字符串,判断是否存在一些字符串是其他字符串的前缀。如:第一组数据 911 是最后一个 91125426 的前缀,故拨打时容易直接播出 911 输出“NO”,反之,输出“YES”。

分析:每读入一个电话号码,判断其第1到n-1位是否有相同的其他号码即可。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <queue>
#include <stdlib.h>
using namespace std;
int T,n;
char num[10005][15],phone[15];
bool flag;
typedef struct TrieNode
{
    bool end;        //标记电话号码结束
    TrieNode *next[10];//数字1到9每个设一个分节点
}Trie;
Trie *root;
void init()  //初始化函数
{
    root=(Trie*)malloc(sizeof(Trie));
    root->end=false;
    for(int i=0;i<10;i++)
        root->next[i]=NULL;
    flag=true;
}
void Insert(char *num)
{
    if(root==NULL&&*num=='\0')
        return ;
    Trie *p=root;
    while(*num!='\0')
    {
        if(p->next[*num-'0']==NULL)
        {
            Trie *t=(Trie*)malloc(sizeof(Trie));
            for(int i=0;i<10;i++)
                t->next[i]=NULL;
            t->end=false;
            p->next[*num-'0']=t;
            p=p->next[*num-'0'];
        }
        else
        {
            p=p->next[*num-'0'];
        }
        num++;
    }
    p->end=true;
}
int Search(char *phone)
{
    Trie *p=root;
    for(int i=0;phone[i]!='\0';i++)
    {
        if(p==NULL||p->next[phone[i]-'0']==NULL)
            return false;  //出现不对应的情况就返回false
        else
            p=p->next[phone[i]-'0'];
    }
    return p->end; 
}
void Del(Trie *root)
{
    for(int i=0;i<10;i++)
    {
        if(root->next[i]!=NULL)
            Del(root->next[i]);
    }
    free(root);
}

int main()
{
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        init();
        for(int i=0;i<n;i++)  //输入n组电话号码
        {
            scanf("%s",num[i]);
            Insert(num[i]);
        }
        for(int i=0;i<n;i++)
        {
            int l=strlen(num[i]);
            memset(phone,'\0',sizeof(phone));
            for(int j=0;j<l-1;j++)  //挨个检测第1到n-1隔数字组成的号码是否有重复
            {
                phone[j]=num[i][j];
                if(Search(phone)) //当返回值为true说明出现过,无需继续检测
                {
                    flag=false;
                    break;
                }
            }
        }
        if(flag) printf("YES\n");
        else printf("NO\n");
        Del(root);       //数据有多组,记得清空字典树
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值