首页 > 代码库 > B - Phone List
B - 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:
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.
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
题目大意:
给出几组字符串,判断每组字符串中是否存在某一个字符串是另外一个字符串的前缀的情况,如果有,就输出NO;如果没有,就输出YES。
输入:第一行一个整数t(1<=t<=40),表示有多少组测试数据;接下来的t组数据中,每组数据的第一行是一个整数n(1<=n<=10000),表示该组的数据个数,接着n行每行一个字符串。
解题思路:
本题可以用字典树求解,但是我采用的是简单的查找。对每组数据,先按字典序对所以字符串排序,然后只需对比每两个相邻的字符串,判断它们是不是存在前缀关系即可。
代码如下:C/C++代码
#include<iostream> #include<stdio.h> #include<algorithm> #include<string> using namespace std; string s[10005]; //判断排序后的相邻的两个字符串是否是一个字符串是是另一个字符串的前缀 bool judge(int n) { int i,j,m; for(i=0;i<n-1;i++) { m=s[i].size(); for(j=0;j<m;j++) { if(s[i][j]!=s[i+1][j]) break; } if(j==m) return false; } return true; } int main() { int t,n,i; scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=0;i<n;i++) cin>>s[i];//只能用cin输入,而不能用scanf输入 //scanf("%s",&s[i]); sort(s,s+n);//按字典序排序 if(judge(n)) printf("YES\n"); else printf("NO\n"); } return 0; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。