zoukankan      html  css  js  c++  java
  • POJ 3630 Trie树 TLE

    动态 Trie 会超时,DISCUSS 中有人提醒要用静态数组的 Trie,还没学;

    这个题要注意除了判断当前串是否有和字典中的串相同的前缀外,还要判断当前串是否是字典中串的前缀;

    -----------------------------------------------------------------

    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

    -----------------------------------------------------------------

    # include <stdio.h>
    
    struct tree{
        tree *node[10];
        int bj;
        tree() {
            bj = 1;
            for (int i = 0; i < 10; ++i)
                node[i] = NULL;
        }
    } *root;
    
    int n;
    char tel[15], ok;
    
    void visit(tree *p, char *s)
    {
        char c = (*s) - '0';
        if (p->node[c])
        {
            p = p->node[c];
            if (!s[1] || p->bj == 0) {ok = 0; return ;}
        }
        else
        {
            p->node[c] = new tree;
            p = p->node[c];
            p->bj = 2;
        }
        if (s[1]) visit(p, s+1);
        else p->bj = 0;
    }
    
    void release(tree *p)
    {
        for (int i = 0; i < 10; ++i)
            if (p->node[i]) release(p->node[i]);
           delete p;
    }
    
    void solve()
    {    
        ok = 1;
        root = new tree;
        scanf("%d", &n);
        for (int i = 1; i <= n; ++i)
        {
            scanf("%s", tel);
            if(ok) visit(root, tel);      
        }
        puts(ok ? "YES":"NO");
        release(root);
    }
    
    int main()
    {
        int T;
        
        scanf("%d", &T);
        while (T--)
        {
            solve();
        }
        
        return 0;
    }

    -----------------------------------------------------------------

  • 相关阅读:
    WebApi接口访问频率控制的实现
    一分钟告诉你究竟DevOps是什么鬼?
    大多数企业不知道的隐形成本
    29个网络营销必须知道的数据
    如何让自己的生活有品质感?
    一则有意思的产品小故事
    免费学习编程的9个地方
    营销,就是营销人性的弱点!
    网络营销行业十大看了就想吐的“滥词”
    高质量的内容是SEO的关键
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2585589.html
Copyright © 2011-2022 走看看