hdu1671 Phone List(简单字典树,注意超空间)

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

题目和hdu1305很像,只是数字从01,变成了0~9,题目数据量也比较大,需要释放空间

#include<iostream>
#include<string>
#include<cstdio>
using namespace std;

const int N=10;
struct Tire
{
    int num;//记录改节点是否是输入字符串的最后一个字符,是赋值-1
    Tire *next[N];
};
Tire *head;//头结点

void Insert(string s)//插入字典树
{
    Tire *T=head,*t;
    int i,j;
    for(i=0;i<s.size();i++)
    {
        int id=s[i]-'0';
        if(T->next[id]==NULL)
        {
            t=new Tire;
            for(j=0;j<N;j++)
            {
                t->next[j]=NULL;
				t->num=0;
            }
            T->next[id]=t;
        }
        T=T->next[id];
    }
	T->num=-1;
}

bool Find(string s)//查找是否有相同前缀,有则返回false
{
    Tire *T=head;
    int count=0,i;
    for(i=0;i<s.size();i++)
    {
        int id=s[i]-'0';
        if(T->next[id]==NULL)
        {
            count=0;
            break;
        }
        else 
        {
            T=T->next[id];
            count=T->num;
        }
		if(i<s.size()-1&&count==-1)return false;
    }
    return true;
}
void freedom(Tire *p)//释放空间
{
    for(int i = 0; i < N; i++)
		if(p -> next[i] != NULL)
			freedom(p -> next[i]);
		free(p);
}
char p[10010][12];
int main()
{
    
    int i,n,T;
	bool flag;
	cin>>T;
	
    while(T--)
    {
        head=new Tire;
	for(i=0;i<N;i++)
	{
		head->next[i]=NULL;
		head->num=0;
	}
        scanf("%d",&n);
		flag=true;
		for(i=0;i<n;i++)
		{
			scanf("%s",&p[i]);
			Insert(p[i]);
			
		}
		for(i=0;i<n;i++)
		{
			if(flag)flag=Find(p[i]);
			else break;
		}
		freedom(head);
		if(flag)printf("YES\n");
		else printf("NO\n");
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值