码迷,mamicode.com
首页 > 其他好文 > 详细

Phone List

时间:2015-08-28 21:37:28      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

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


题解:找字符串(不能太长)前缀首先想到字典树,但是这道题卡动态字典树,需要静态字典树。需要将内存分配为全局数组。


#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

struct Node
{
	bool isStr;
	Node* next[10];
	Node()
	{
		isStr = false;
		for(int i = 0;i < 10;i++)
		{
			next[i] = NULL;
		}
	}
};

Node* root;
Node arr[1000005];
int k;

bool insert(char* s)  //判断该字符串是其他串的前缀和其他串是该字符串的前缀 
{
	int len = strlen(s);
	Node* p = &arr[0];
	bool f = false;
	for(int i = 0;i < len;i++)
	{
		int x = s[i] - '0';
		if(p->next[x] == NULL)
		{
			p->next[x] = &arr[k++];
			f = true;
		}
		p = p->next[x];
		if(p->isStr)
		{
			return true;
		}
	}
	if(!f)
	{
		return true;
	}
	p->isStr = true;
	return false;
}

int main()
{
	char s[100];
	int ncase;
	cin>>ncase;
	while(ncase--)
	{
		k = 1;
		int n;
		scanf("%d",&n);
		bool flag = false;
		for(int i = 0;i < n;i++)
		{
			scanf("%s",s);
			if(!flag && insert(s))
			{
				flag = true;
			}
		}
		if(flag)
		{
			printf("NO\n");
		}
		else
		{
			printf("YES\n");
		}
		for(int i = 0;i < k;i++)
		{
			arr[i].isStr = false;
			for(int j = 0;j < 10;j++)
			{
				arr[i].next[j] = NULL;
			}
		}
	}
	
	
	return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

Phone List

标签:

原文地址:http://blog.csdn.net/wang2534499/article/details/48056597

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!