您的位置:首页 > 其它

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

2014-05-18 13:51 281 查看
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
;
};
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: