hdu 1671 Phone List

Phone List

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

Problem Description
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.

Input
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.

Output
For each test case, output “YES” if the list is consistent, or “NO” otherwise.

Sample Input
 
   
 
    
2 3 911 97625999 91125426 5 113 12340 123440 12345 98346
Sample Output
 
   
NO
YES
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1671
题目大意:给n个号码,拨通任意一个时不会打通另一个,也就是任意一个号码不是另一个的前缀。
解题思路:字典树查找判断。插入每个号码完成后,号码的最后一个数字打上标记,在插入号码过程中,如果号码还未插入完成该位置就已经做过标记,则说明该前缀已作为另一个号码存在,即不合法。如果号码在插入的整个过程中每个节点都不为空,则说明该号码已是另一个号码的前缀,即不合法。
代码如下:
#include 
#include 
char s[10];
bool flag;
struct node 
{
    bool end;
    node *next[10];
    node()
    {
        memset(next,NULL,sizeof(next));
        end=false;
    }
};
void Insearch(node *p,char *s)
{
    int p1=0;    //判断号码插入的整个过程中节点是否有空的情况
    for(int i=0;s[i]!='\0';i++)
    {
        int a=s[i]-'0'; 
		if(p->end)flag=false;   //该位置已被标记过,说明已经有号码是该号码的子串了
        if(p->next[a]==NULL)
        {
            p->next[a]=new node();
            p1=1;
        }
        p=p->next[a];
    }
    if(!p1)flag=false; //节点没有空的情况,说明该号码已是另一个号码的前缀了
    p->end=true;    //一个号码插入完成打上标记
}
void clear(node *p)   //释放空间,这题必须!否则会超内存,递归实现
{
	for(int i=0;i<10;i++)
		if(p->next[i])
			clear(p->next[i]);
	delete p;
}
int main()
{
    int n,t;
    scanf("%d",&t);
    while(t--)
    {
        flag=true;       //判断该组号码是否合法
        scanf("%d",&n);
        node *root=new node();
        while(n--)
        {
            scanf("%s",s);
            if(!flag)continue;
            Insearch(root,s);
        }
        if(!flag)
            printf("NO\n");
        else
            printf("YES\n");
		clear(root);
    }
    return 0;
}


你可能感兴趣的:(ACM_数据结构)