您的位置:首页 > 其它

HDOJ-1671 Phone List 字典树的应用----判断一组字符串中是否有一个字符串是另一个字符串的前缀(字典树第二类应用)。

2012-08-09 18:07 525 查看

Phone List

Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5081 Accepted Submission(s): 1714


[align=left]Problem Description[/align]
Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let’s say the phone catalogue listed these numbers:
1. Emergency 911
2. Alice 97 625 999
3. Bob 91 12 54 26
In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent.

[align=left]Input[/align]
The first line of input gives a single integer, 1 <= t <= 40, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 <= n <= 10000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.

[align=left]Output[/align]
For each test case, output “YES” if the list is consistent, or “NO” otherwise.

[align=left]Sample Input[/align]

2 3 911 97625999 91125426 5 113 12340 123440 12345 98346

[align=left]Sample Output[/align]

NO YES

/* 功能Function Description:     HDOJ-1671   字典树问题
开发环境Environment:          DEV C++ 4.9.9.1
技术特点Technique:
版本Version:
作者Author:                   可笑痴狂
日期Date:                      20120809
备注Notes:
这道题就是判断一组字符串中是否有一个字符串是另一个字符串的前缀
注意有两种情况
*/
#include<stdio.h>
#include<string.h>

typedef struct node
{
int num;    //标记该字符是否是某一字符串的结尾
struct node *next[10];
}node;

node memory[1000000];
int k;

int insert(char *s,node *T)
{
int i,len,id,j;
node *p,*q;
p=T;
len=strlen(s);
for(i=0;i<len;++i)
{
id=s[i]-'0';
if(p->num==1)   //说明存在先前字符可以作为s的前缀----(先短后长)
return 1;
if(p->next[id]==NULL)
{
q=&memory[k++];
q->num=0;
for(j=0;j<10;++j)
q->next[j]=NULL;
p->next[id]=q;
}
p=p->next[id];
}
for(i=0;i<10;++i)      //如果p的后继结点不为空的话说明s时先前字符的前缀----(先长后短)
if(p->next[i]!=NULL)
return 1;
p->num=1;
return 0;
}

int main()
{
int m,n,flag,i;
node *T;
char s[15];
scanf("%d",&m);
while(m--)
{
k=0;          //每次都从数组下标为0的地方开始分配内存,可以使内存循环利用,从而不会造成内存超限
T=&memory[k++];
T->num=0;
for(i=0;i<10;++i)
T->next[i]=NULL;
flag=0;
scanf("%d",&n);
while(n--)
{
scanf("%s",s);
if(flag)
continue;
if(insert(s,T))
flag=1;
}
if(flag)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐