zoukankan      html  css  js  c++  java
  • [ICPC2019上海B] Prefix Code

    [ICPC2019上海B] Prefix Code - Trie

    Description

    给定 n 个串,问是否存在两个串满足其中一个串是另一个串的前缀。不存在输出 Yes,存在输出 No。(字符串最大长度为 10 ,只包含字符 ‘0’ 到 ‘9’)

    Solution

    把所有前缀都插入字典树,然后枚举每个原串判断即可

    #include <bits/stdc++.h>
    using namespace std;
    
    #define int long long
    
    struct Trie
    {
        struct Node
        {
            int ch[10];
            int val;
        };
    
        vector<Node> nodes;
        int ind = 0;
    
        Trie(int siz)
        {
            nodes.resize(siz);
        }
    
        void insert(const string &str)
        {
            int p = 0;
            for (int i = 0; i < str.length(); i++)
            {
                char c = str[i] - '0';
                nodes[p].val++;
                if (nodes[p].ch[c] == 0)
                    nodes[p].ch[c] = ++ind;
                p = nodes[p].ch[c];
            }
            nodes[p].val++;
        }
    
        int query(const string &str)
        {
            // 检查 str 是否作为一个前缀(不是自己)出现过
            int p = 0;
            for (int i = 0; i < str.length(); i++)
            {
                char c = str[i] - '0';
                p = nodes[p].ch[c];
            }
            return nodes[p].val > 1;
        }
    };
    
    void solve()
    {
        int n;
        cin >> n;
        Trie trie(n * 12);
        vector<string> strs(n + 2);
        for (int i = 1; i <= n; i++)
            cin >> strs[i];
        for (int i = 1; i <= n; i++)
            trie.insert(strs[i]);
        for (int i = 1; i <= n; i++)
            if (trie.query(strs[i]))
            {
                cout << "No" << endl;
                return;
            }
        cout << "Yes" << endl;
    }
    
    signed main()
    {
        ios::sync_with_stdio(false);
        int t;
        cin >> t;
        for (int i = 1; i <= t; i++)
        {
            cout << "Case #" << i << ": ";
            solve();
        }
    }
    
  • 相关阅读:
    C#的集合类(二)Hashtable、SortedList、Dictionary
    下载文件-JavaScript
    ASP.NET(C#)图片加文字、图片水印
    C# DataTable 互转 List<T>
    C# 将 DataTable 转 List<T>、首行转 T
    C# 金额转中文大写
    监听端口守护进程
    数据库操作的九大步骤
    日志方法
    sqlserver 查找所有子级
  • 原文地址:https://www.cnblogs.com/mollnn/p/14571206.html
Copyright © 2011-2022 走看看