列表

详情


NC51009. Phone List

描述

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:
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.

输入描述

The first line of input gives a single integer, , the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, . Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.

输出描述

For each test case, output "YES" if the list is consistent, or "NO" otherwise.

示例1

输入:

2
3
911
97625999
91125426
5
113
12340
123440
12345
98346

输出:

NO
YES

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++(g++ 7.5.0) 解法, 执行用时: 100ms, 内存消耗: 14236K, 提交时间: 2022-11-08 20:17:09

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=1e5+10;
int trie[N][30], val[N], k, flag;
void init()
{
	memset(trie, 0, sizeof trie);
	memset(val, 0, sizeof val);
	k = 0;
	flag = 1;
}
void insert(string s)
{
	if(flag == 0) return ; 
	int p = 0;
	int len = s.size();
	for(int i = 0; i < len; i++)
	{
		int u = s[i] - '0';
		if(trie[p][u] == 0) trie[p][u] = ++k;
		p = trie[p][u];
		if(val[p] == 1)
		{
			flag = 0;
			return ;
		}
	}
	val[p] = 1;
	if(p != k) flag = 0;
}
int main()
{
	string s1;
	int t, n;
	cin >> t;
	while(t--)
	{	
		init();
		cin >> n;
		for(int i = 1; i <= n; i++)
		{
			cin >> s1;
			insert(s1);
		}
		if(flag) cout << "YES\n";
		else cout << "NO\n";
	}
	return 0;
}

C++ 解法, 执行用时: 71ms, 内存消耗: 3456K, 提交时间: 2022-01-16 11:19:30

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int t;
	cin>>t;
	string s[100003];
	while(t--)
	{
		int n;
		cin>>n;
		for(int i=0;i<n;i++)
		cin>>s[i];
		sort(s,s+n);
		int q=0;
		for(int i=0;i<n;i++)
		{
			string a,b;
			a=s[i],b=s[i+1];
			if(b.find(a)==0)
			  q=1;
		}
		if(q)
		cout<<"NO"<<endl;
		else
		cout<<"YES"<<endl;
	}
}

上一题