首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【POJ】3630 - Phone List(字典树(静态建树))

【POJ】3630 - Phone List(字典树(静态建树))

作者头像
FishWang
发布2025-08-26 20:00:28
发布2025-08-26 20:00:28
1790
举报

点击打开题目

Phone List

Time Limit: 1000MS

Memory Limit: 65536K

Total Submissions: 27567

Accepted: 8263

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

代码语言:javascript
复制
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346

Sample Output

代码语言:javascript
复制
NO
YES

Source

Nordic 2007

分析就不多说了,看上一篇博客,说的很详细:点击打开链接

但是这个题是POJ的,数据比较厉害,动态存图会TLE(果然省时间就给费空间,省空间就得费时间)

其实静态存图就是先开一定的空间给字典树,完了往后依次取空间即可。

代码如下:

代码语言:javascript
复制
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define idx(x) (x-'0')
bool ans;
struct Trie
{
	Trie *next[10];
	int v;
	void init()
	{
		v = 0;
		for (int i = 0 ; i <= 9 ; i++)
			next[i] = NULL;
	}
}tree[1<<16];
int ant;
void insert(char *s)
{
	int l = strlen(s);
	Trie *p = &tree[0], *q;
	for (int i = 0 ; i < l ; i++)
	{
		int id = idx(s[i]);
		if (p->next[id] == NULL)
		{
			if (p->v == -1)		//若在该点有字符串结束,那么那个字符串为该串的前缀 
			{
				ans = false;
				return;
			}
			q = &tree[ant++];
			p->next[id] = q;
		}
		p = p->next[id];
	}
	p->v = -1;		//这个-1表示一个字符串已经结束 
	for (int i = 0 ; i < 10 ; i++)
	{
		if (p->next[i] != NULL)
		{
			ans = false;		//如果该点不是叶子,则它为别的串的前缀 
			return;
		}
	}
}
void del(int n)
{
	for (int i = 1 ; i < ant ; i++)
		tree[i].init();
}
int main()
{
	int u;
	int n;
	char s[15];
	scanf ("%d",&u);
	while (u--)
	{
		ans = true;
		tree[0].init();
		ant = 1;
		scanf ("%d",&n);
		for (int i = 0 ; i < n ; i++)
		{
			scanf ("%s",s);
			if (ans)
				insert(s);
			else
				continue;		//如果之前的号码已经出现问题,那么直接继续输入就行了 
		}
		if (ans)
			printf ("YES\n");
		else
			printf ("NO\n");
		del(ant);
	}
	return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档