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 the case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialed the first three digits of bob’s phone number. So this list would not be sonsistent.
Input
The first line of input gives a single integer, 1<=t<=40, the number of test cases. Each test starts with n, the number of phone numbers, on a separate line, 1<=n<=10000. Then follows n linss with one unique phone numbers 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 1
2 3 911 97625999 91125426 5 113 12340 123440 12345 98346
Sample Output 1
NO YES
解题思路:
一开始我使用暴力解题——将每一个电话号码都与其余进行比较,果不其然的超时了。要解决超时的问题,那就要优化啦。优化的方法就是先将所有的电话号码根据字典序排序,使得每两个电话号码之间的相似度最高,这样我们只需要对相邻的两个电话号码进行比较就OK啦!
我先是尝试用char型二维数组储存这些电话号码,但在排序的时候就会比较麻烦,因为非常好用的sort函数没办法对char型二维数组排序......
所以可以再设一个数组去索引每个电话号码,代码如下
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
char a[10005][11];
bool cmp(int x,int y){
return strcmp(a[x],a[y])<0;//按照字典序排序
}
int main()
{
int n,m,i,j;
cin>>n;
while(n--){
cin>>m;
int b[m];
for(i=0;i<m;i++){
cin>>a[i];//储存每个电话号码
b[i]=i;//b数组用于sort排序时索引a的下标,这样就能解决不可以直接对a数组排序的问题
}
sort(b,b+m,cmp);
int l1=strlen(a[b[0]]);//读取电话号码的长度
int flag;
for(i=0;i<m-1;i++){
flag=0;
int l2=strlen(a[b[i+1]]);
for(j=0;j<min(l1,l2);j++){
if(a[b[i]][j]!=a[b[i+1]][j]){
flag=1;//如果一个电话号码是另一个电话号码的前缀则flag=0,反之则为1
break;
}
}
if(flag==0){
break;
}
l1=l2;
}
if(flag==0)cout<<"NO"<<endl;
else cout<<"YES"<<endl;
}
return 0;
}
当然也可以不用char数组,C++的string它不香吗哈哈哈哈哈哈哈
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
string a[10005];
bool cmp(string x,string y){
return x<y;
}
int main()
{
int n,m,i;
cin>>n;
while(n--){
cin>>m;
for(i=0;i<m;i++){
cin>>a[i];
}
sort(a,a+m,cmp);
int flag=0;
for(i=0;i<m-1;i++){
int l=min(a[i].size(),a[i+1].size());
if(a[i].substr(0,l)==a[i+1].substr(0,l)){ //substr是截取字符串的函数
flag=1;
}
}
if(flag==1)cout<<"NO"<<endl;
else cout<<"YES"<<endl;
}
return 0;
}
是不是看起来简洁好懂多了哈哈哈哈哈哈哈哈