1. 程式人生 > >HDU 1671 Phone List(字典樹)

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.

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;
}