hdu 1671 Phone List

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

字典树的经典题目。

关于字典树的理解:http://kymowind.blog.163.com/blog/static/18422229720114264416738/

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
typedef struct tree
{
    tree* next[10];
    int num;
}node;
node* head ;
int flag;
void insert(char * str)
{
    node *t , *s = head;
    int len = strlen(str);
    int f = 0;//设置标记变量,用来检验是否创建了新的节点,如果创建了新的节点,
                //它 肯定不会是其他字符串的前缀
    for(int i = 0; i < len; i++)
    {

        int id = str[i] - '0';
        if(s->next[id] == NULL)//如果找不到要插入的字母,则创建该节点
        {
            f = 1;
            t = new node;
            for(int j = 0; j < 10; j++)
                t->next[j] = NULL;
            t->num = 0;
            s->next[id] = t;
        }
        s = s->next[id];
        if( s->num ) flag = 1;// 如果该点的num  非 0 说明,此节点是某个单词的结尾。
    }
    if(!f) flag = 1;// 如果该字符串搜索完毕,仍然没有创建新的节点。他是其他单词的前缀
    if(s->num) flag = 1;
    s->num = 1;
}
void freedom(node *p)//从根结点开始,递归free
{
    int i=0;
    for(i=0;i<10;i++)
        if(p->next[i]!=NULL)
            freedom(p->next[i]);
    free(p);
}
int find(char* str)
{
    node *s = head;
    int len = strlen(str);
    for(int i = 0; i < len; i++)
    {
        int id = str[i] - 'a';
        if(s->next[id] == NULL)
            return 0;
        s = s->next[id];
    }
    return s->num;
}

int main()
{
    int T,n;
    cin>>T;

    char s[50];
    while(T--)
    {
        head = new node;
        for(int i = 0; i <= 9; i++)
        {
            head->next[i] = NULL;
        }
        head->num = 0;
        cin>>n;
        flag = 0;
        while(n--)
        {

            scanf(" %s",s);//这个地方一定要注意,当  接受的数据过大时,不能用cin
            //cin>>s;
            if(!flag)//设置变量,如果出现不符合题意的情况,停止插入,可以节省时间
            insert(s);
        }
        if(flag) cout<<"NO"<<endl;
        else  cout<<"YES"<<endl;
        freedom(head);//释放节点,否则会爆栈

    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值