HDU1671 Phone List

该博客讨论了如何判断一个电话号码列表是否一致,即没有号码是另一个号码的前缀。通过给出的样例输入和输出,解释了判断逻辑,并提到了使用静态数组来优化解决方案,以避免动态内存分配导致的时间消耗。代码在ACM竞赛中实现了94毫秒的运行时间和14400KB的内存占用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目: 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:

Emergency 911
Alice 97 625 999
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。

思路:链表版会超时。每次都动态创建内存,比较耗时间,当然可以考虑把链表存储起来。那么就直接考虑用静态数组。
但是需要注意的是用这个模板就要考虑到开数组的问题。因为每个电话号码最多有十位数字。每次测试数据最多有10000个电话号码。所以数组就要开到1e5。但是开到65000也可过。因为这题数据还不是很大。代码AC时间为 94毫秒,内存14400

#include<cstdio>
#include<cstring>
#include<memory.h>
#include<algorithm>

using namespace std;
const unsigned short Max=65000;
unsigned short letters;
unsigned short node[Max][11];
bool flag[Max];
int getIndex(char a){
    return a-'0';
}
bool put(char *s){
    bool mark=false;
    int index,len=strlen(s),next=0;
    for(int i=0;i<len;i++){
        index=getIndex(s[i]);
        if(!node[next][index]){
            mark=true;
            flag[letters]=false;
            node[next][index]=letters++;
        }
        next=node[next][index];
        if(flag[next])return false;
    }
    flag[next]=true;
    if(!mark)return false;
    return true;
}
int main(){
    int times,n;
    char s[11];
    scanf("%d",&times);
    while(times--){
        letters=1;
        scanf("%d",&n);
        bool b=true;
        for(int i=0;i<n;i++){
            scanf("%s",s);
            if(b)
                b=put(s);
        }
        if(b)
            printf("YES\n");
        else
            printf("NO\n");
        for(int i=0;i<letters;i++){
            memset(node[i],0,sizeof(node[i]));
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值