您的位置:首页 > 其它

hdu1671 PhoneList (字典树)

2014-08-07 21:52 337 查看
题目链接://http://acm.hdu.edu.cn/showproblem.php?pid=1671

Phone List

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 10255    Accepted Submission(s): 3506


[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

查找公共前缀,基本的字典树应用,记得释放内存,MLE两次,忘记加释放内存的函数了==

//http://acm.hdu.edu.cn/showproblem.php?pid=1671
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int flag;
struct Node
{
struct Node *next[10];
};

struct Node* newNode()
{
struct Node* p = (struct Node *)malloc(sizeof(struct Node));

int i;
for(i=0; i<=9; i++)
{
p->next[i]=NULL;
}
return p;
};

void insert(char *str,struct Node *root)
{
int k = strlen(str);
int i,index;
struct Node* now;
struct Node* child;

now=root;

for(i=0; i<k; i++)
{
index = str[i]-'0';

if(now->next[index]==NULL)
{
child=newNode();
now->next[index]=child;
now=child;
}
else
{
now=now->next[index];
}
}
}

int find(char *str,struct Node *root)
{
int k = strlen(str);
int i,index;
struct Node* now = root;

for(i=0;i<k;i++)
{
index = str[i]-'0';
now=now->next[index];
}

for(i=0;i<10;i++)
{
if(now->next[i] != NULL)
{
return 1;
}
}
return 0;
}

void release(struct Node* root)
{
int i;

if (NULL == root)
{
return;
}
for (i = 0; i < 10; i++)
{
if ( root->next[i] != NULL )
{
release( root->next[i] );
}
}

free( root );
root = NULL;
}

int main()
{
int n;
scanf("%d",&n);
char digit[10005][11];

while(n--)
{struct Node* root = newNode();
int m;
flag=0;
scanf("%d",&m);
int i;
for(i=0; i<m; i++)
{
scanf("%s",digit[i]);
insert(digit[i],root);
}
for(i=0;i<m;i++)
{
if(find(digit[i],root)==1)
{

printf("NO\n");
break;
}

}
if(i==m)
printf("YES\n");
release(root);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: