Phone Number[2010年山东省第一届ACM大学生程序设计竞赛]

题目链接
Problem Description

We know that if a phone number A is another phone number B’s prefix, B is not able to be called. For an example, A is 123 while B is 12345, after pressing 123, we call A, and not able to call B.
Given N phone numbers, your task is to find whether there exits two numbers A and B that A is B’s prefix.

Input

The input consists of several test cases.
The first line of input in each test case contains one integer N (0<N<1001), represent the number of phone numbers.
The next line contains N integers, describing the phone numbers.
The last case is followed by a line containing one zero.
Output

For each test case, if there exits a phone number that cannot be called, print “NO”, otherwise print “YES” instead.
Sample Input

2
012
012345
2
12
012345
0

Sample Output

NO
YES

解题思路:
暴力求解

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
bool IsPrefix(char number[],char text[]){//判断number是否是text的前缀
    //小于两个值中最小的那个
    for(int i = 0;i < min(strlen(number),strlen(text));i++)
        if(number[i] != text[i])
            return false;
    return true;
}
int main(){
    int n,flag;
    char number[1005][105];
    while(~scanf("%d",&n)){
        if(!n)
            break;
        flag = 0;
        for(int i = 0;i < n;i++)
            scanf("%s",number[i]);
        for(int i = 0;i < n;i++){
            for(int j = 0;j < n;j++)
                if(i != j && IsPrefix(number[i],number[j])){
                    printf("NO\n");
                    flag = 1;
                    break;
                }
            if(flag)
               break;
        }
        if(!flag)
            printf("YES\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37708702/article/details/80158934