zoukankan      html  css  js  c++  java
  • POJ

    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

    题意:输入n个号码,只要输入的号码中有一个是另一个的前缀即输出NO,否则输出YES

    用字典树实现,在建树同时检查每次插入到号码是否有前缀重复或整串号码是别的号码的前缀
    记得清空树,因为空间较大,因此用到某个节点的时候再清空,不用每次都整树清空。

    #include<stdio.h>///字典树建树同时检索
    #include<string.h>
    int tot,tre[100040][12];///号码只有0-9因此比26个字母还要简单
    bool vis[100050],ans;
    int insert(char str[],int rt)
    {///要预防两种前缀重复的情况,一种是短的先出现,一种是长的先出现,如911和911245
        int len=strlen(str);
        for(int i=0; i<len; i++)
        {
            int x=str[i]-'0';
            if(tre[rt][x]==0)
            {
                tre[rt][x]=++tot;
                memset(tre[tre[rt][x]],0,sizeof(tre[tre[rt][x]]));///有t次输入,因此不清空树会造成混乱,因此每次申请新的节点要清空当前节点的孩子
            }
            rt=tre[rt][x];
            if(vis[rt]==true)ans=false;///预防短的号码先出现,在建长号码的树时时刻检查当前路过的节点rt是否曾被作为结束位置
        }///不用排序,在两处判断即可,注意这里是rt<tot!!
        if(rt<tot)ans=false;///预防长的号码先出现,如果这个短号码的的最终结束节点是曾被长串走过的一个节点,也就是说这个节点上标记的号数小于最大节点号数
        vis[rt]=true;///则说明这个终结节点曾被走过,此短号码是已出现长号码的前缀!
    }
    int main()
    {
        int t,n,num;
        char phone[12];
        scanf("%d",&t);
        while(t--)
        {
            tot=0;
            num=++tot;
            ans=true;
            memset(vis,false,sizeof(vis));
            memset(tre[num],0,sizeof(tre[num]));///这里是num也行是tot也行
            scanf("%d",&n);
            for(int i=0; i<n; i++)///在建树同时检索之前的号码是否和前缀重复
            {
                scanf("%s",phone);
                insert(phone,num);
            }
            printf("%s
    ",ans?"YES":"NO");
        }
    }
    
  • 相关阅读:
    curl命令
    sublime 光标选中多行
    mysql删除重复记录并且只保留一条
    Laravel 如何实现 Excel 导入及导出功能
    laravel中DB查询数据库后,返回的对象转为数组
    【文件上传/解析技巧拓展】————1、我的WafBypass之道(Upload篇)
    【文件包含技巧拓展】————5、文件包含漏洞(绕过姿势)
    【文件包含技巧拓展】————4、文件包含漏洞(下)
    【文件包含技巧拓展】————3、文件包含漏洞(上)
    【文件包含技巧拓展】————2、zip或phar协议包含文件
  • 原文地址:https://www.cnblogs.com/kuronekonano/p/11135860.html
Copyright © 2011-2022 走看看