Phone List(简单字典树或暴力)

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:

  • Emergency 911
  • Alice 97 625 999
  • 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

题目大意:给出多组数据,每组多个电话号码(数字串)。判断是否造成打错电话:2个号码123    123456 前3个数字相同,并且构成了一个完整的号码串即可打出。

思路:不会字典树,第一反应当然是暴力喽。然后细细一想,既然是判断相同串是否存在,那我直接将串进行排序将第一位相同的串排在一起再进行判断操作,就大大优化了搜索时间。该题在hdu1671数据范围为10000,nyoj163数据范围为100000,本以为在nyoj上应该过不了,结果还是过了,时间比较少,只能说该题的bug吧。标答字典树。

暴力代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
string s[100005];
int main()
{
	char p[12];
	int t,flag=0,n,i,j;
	scanf("%d",&t);
	while(t--)
	{
		flag=0;
		scanf("%d",&n);
		for(int i=0;i<n;i++)
		{
			scanf("%s",&p);
			s[i]=p;
		}
		sort(s,s+n);
		for(int i=1;i<n;i++)
		{
			if(s[i].size()>s[i-1].size())
			{
				for(j=0;j<s[i-1].size();j++)
				   if(s[i][j]!=s[i-1][j])
				       break;
			    if(j==s[i-1].size())
			       flag=1; 
			}
		}
		if(flag) printf("NO\n");
		else printf("YES\n");
	}
	return 0;
}

字典树代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef struct tree{
    int endd;
    tree *next[10];
    tree(){
        endd=0;
        memset(next,NULL,sizeof(next));
    }
};
tree *root;

int inser(char a[]){
    int flag=0;
    tree *p=root;
    int k;
    int len=strlen(a);
    for(int i=0;i<len;i++){
        k=a[i]-'0';
        if(p->next[k]==NULL){
            p->next[k]=new tree;
            flag=1;
        }
        p=p->next[k];
        if(p->endd){
            return 0;
        }
    }
    p->endd=1;
    if(!flag){
        return 0;
    }
    return 1;
}

int main()
{
    int t;
    char a[10];
    scanf("%d",&t);
    while(t--){
        int n;
        int flag=1;
        root=new tree();
        scanf("%d",&n);
        while(n--){
            scanf("%s",a);
            if(flag){
                flag=inser(a);
            }
        }
        if(!flag){
            printf("NO\n");
        }else{
            printf("YES\n");
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/pleasantly1/article/details/81012491