(hdu step 5.2.3)Phone List(在一堆号码中,判断是否有号码是其它号码的前缀)

来源:互联网 发布:java在数据库中写的表 编辑:程序博客网 时间:2024/04/29 19:41


题目:

Phone List

Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 235 Accepted Submission(s): 92 
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
2391197625999911254265113123401234401234598346
 
Sample Output
NOYES
 
 
Source
2008 “Insigma International Cup” Zhejiang Collegiate Programming Contest - Warm Up(3)
 
Recommend
lcy


题目分析:

               这道题,属于Trie的入门级别的题目。但是在这里先介绍一下不用Trie怎么解决这道题。在一堆号码中,

要判断一个号码是否是其他号码的前缀。我们可以先对这对号码按字典序进行一下排序。然后依次判断相邻两个号码中是否有号码是其它号码的前缀即可。整体的时间复杂度要比暴力做法的O(n^2)要好很多。


这里还需要介绍一下的是strncmp这个函数。

       strncmp(): 这个函数用来比较s1和s2字符串,这个函数将返回一个值, 它的符号与第一对不同的字符的比较结果相关。如果两个字符串相等的话,strncmp将返回0。如果s1是s2的一个子串的话,s1小于s2。此外还有,函数 int strncmp (const char *s1, const char *s2, size_t size) 此函数与strcmp极为类似。不同之处是,strncmp函数是指定比较size个字符。也就是说,如果字符串s1与s2的前size个字符相同,函数返回值为0。


代码如下:

/* * c.cpp * *  Created on: 2015年3月7日 *      Author: Administrator */#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int maxn = 10001;char num_str[maxn][11];//用于存储号码字符串/** * 让号码字符串按字典序升序排列 */int cmp(const void* a,const void* b){return strcmp((char*)a,(char*)b);}int main(){int t;scanf("%d",&t);while(t--){int n;scanf("%d",&n);int i;for(i = 0 ; i < n ; ++i){//依次读入n个号码scanf("%s",num_str[i]);}qsort(num_str,n,sizeof(num_str[0]),cmp);//将n个号码按字典序排列bool flag = false;//用于标记是否有号码是其他号码的前缀for(i = 0 ; i < n-1 ; ++i){//遍历所有的号码字符串 //如果有号码的前n个字符与其他号码的前n个字符是一样的.if(strncmp(num_str[i],num_str[i+1],strlen(num_str[i] )) == 0){flag = true;//.则表明该号码是另外一个号码的前缀break;//跳出循环}}if(flag == true){//如果由号码是其它号码的前缀printf("NO\n");//打印NO}else{//如果没有号码是其它号码的前缀printf("YES\n");//打印YES}}return 0;}




















1 0
原创粉丝点击