HDU 1671 Phone List(字典树)

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.

扫描二维码关注公众号,回复: 2572060 查看本文章

Sample Input

2 3 911 97625999 91125426 5 113 12340 123440 12345 98346

Sample Output

NO

YES

PS:字典树模板题,只要判断字符串里,有没有单词是其他单词的前缀,有的话输出NO,没有输出YES。

AC代码:

#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include<cmath>
#include<stack>
#include<string>
const int maxn=1e4+100;
const int mod=1e9+7;
const int inf=1e9;
#define me(a,b) memset(a,b,sizeof(a))
typedef long long ll;
using namespace std;
struct node
{
    int flog,s;
    node *next[11];
    node()///初始化
    {
        flog=0,s=0;
        me(next,0);
    }
};
node *root;
int flog;
void insert(char *s)
{
    node *p=root;
    for(int i=0;i<strlen(s);i++)
    {
        int k=s[i]-'0';
        if(p->next[k]!=NULL)
        {
           p->flog=1;
           p=p->next[k];
           if(p->s==-1)///别的单词是这个单词的前缀。
               flog=1;
        }
        else
        {
            node *q=new node();
            p->flog=1;
            p->next[k]=q;
            p=q;
        }
    }
    p->s=-1;
    if(p->flog)///当前单词是前面出现单词的前缀。
        flog=1;
}
void fre(node *p)///释放空间
{
    for(int i=0;i<10;i++)
    {
        if(p->next[i]!=NULL)
            fre(p->next[i]);
    }
    free(p);
}
int main()
{
    char str[15];
	int t,n;cin>>t;
	while(t--)
	{
	    cin>>n;
	    root=new node();
	    flog=0;
	    for(int i=0;i<n;i++)
        {
            scanf("%s",str);
            if(flog)
                continue ;
            insert(str);
        }
        if(!flog)
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;
        fre(root);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41292370/article/details/81318439
今日推荐