现在的位置: 首页 > 综合 > 正文

hdu1671 && POJ——Phone List

2019年02月18日 ⁄ 综合 ⁄ 共 2339字 ⁄ 字号 评论关闭
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
 

Source
 

Recommend

1.字典树法,每次插入一个字符串,在结束位置标记,下次插入的时候,判断,如果前缀在之前就插入了,那么插入现在的字符串,到前缀结束的那个节点上定有标记,如果前缀后插入,那么当把前缀插入完成以后,指向当前节点的指针的所有next指针必定不都为0
ps:这个方法在hdu上能过,但是在POJ上超时

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

using namespace std;

struct dic
{
	dic *next[13];
	int num;
	dic():num(0){memset(next,0,sizeof(next));}
};

dic *root;
bool flag;
void insert(char *s1)
{
	int len=strlen(s1);
	dic *p=root;
	for(int i=0;i<len;i++)
	{
		if(p->next[s1[i]-'0']==0)
		{
			dic *q=new dic;
			p->next[s1[i]-'0']=q;
			p=p->next[s1[i]-'0'];		
		}
		else
		{
			p=p->next[s1[i]-'0'];
			if(p->num==1)
			{
				flag=true;
				return ;
			}
		}
	}
	p->num=1;//标记一个串已经在树上
	for(int i=0;i<10;i++)
		if(p->next[i]!=0)
		{
			flag=true;
			return ;
		} 
}

void Delete(dic *p)
{
	for(int i=0;i<10;i++)
	{
		if(p->next[i]!=0)
			Delete(p->next[i]);
	}
	free(p);
}
int main()
{
	int t;
	int n;
	scanf("%d",&t);
	char digits[14];
	while(t--)
	{
		root=new dic;
		flag=false;
		scanf("%d",&n);
		for(int i=0;i<n;i++)
		{
			scanf("%s",digits);
			if(!flag)
				insert(digits);
		}
		if(flag)
			printf("NO\n");
		else
			printf("YES\n");
		Delete(root);
	}
	return 0;
}

2.排序,参考某大牛,点击打开链接

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>

using namespace std;

char number[10010][15];

int cmp(const void *a,const void *b)
{
	return strcmp((char*)a,(char*)b);
}

int main()
{
	int n,t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d",&n);
		for(int i=0;i<n;i++)
			scanf("%s",number[i]);
		qsort(number,n,sizeof(number[0]),cmp);
		bool flag=false;
		//for(int i=0;i<n;i++)
		//	puts(number[i]);
		for(int i=0;i<n-1;i++)
		{
			if(strncmp(number[i],number[i+1],strlen(number[i]))==0)
			{
				flag=true;
				break;
			}
		}
		if(flag)
			printf("NO\n");
		else
			printf("YES\n");
	}
	return 0;
}

抱歉!评论已关闭.