zoukankan      html  css  js  c++  java
  • POJ3630 Phone List

    题目链接

    分析:

    之前做过类似的题,用的字典树链表写法,今天在训练指南上学了字典树数组的写法。

    #include <iostream>
    #include <cstdlib>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <vector>
    
    using namespace std;
    
    const int maxnode = 10000*10+10;
    const int sigma_size = 10;
    
    struct Trie {
        int ch[maxnode][sigma_size];
        bool val[maxnode];
        int sz;
    
        int idx(char c) { return c - '0'; }
        void init() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); }
    
        bool insert(char *s) {
            int u = 0, len = strlen(s);
            for(int i=0; i<len; i++){
                int c = idx(s[i]);
    
                if(i == len-1 && ch[u][c]) return false;
                if(!ch[u][c]) {
                    memset(ch[sz], 0, sizeof(ch[sz]));
                    val[sz] = false;
                    ch[u][c] = sz++;
                }
                u = ch[u][c];
                if(val[u]) return false;
            }
            val[u] = true;
            return true;
        }
    }trie;
    
    int main(){
        int T, n, flag;
        char s[15];
    
        cin >> T;
        while(T--) {
            flag = 1;
            trie.init();
    
            scanf("%d", &n);
            while(n--){
                scanf("%s", s);
                if(flag){
                    if(!trie.insert(s)) flag = 0;
                }
            }
    
            if(flag) printf("YES\n");
            else printf("NO\n");
        }
    
        return 0;
    }

     另一种写法(非字典树):

    #include <iostream>
    #include <cstdlib>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <vector>
    
    using namespace std;
    
    int main(){
        int T, n, flag;
        string s;
    
        vector<string> q;
    
        cin >> T;
        while(T--) {
            q.clear();
            flag = 1;
    
            scanf("%d", &n);
            for(int i=0; i<n; i++) {
                cin >> s;
                q.push_back(s);
            }
    
            sort(q.begin(), q.end());
            for(int i=0; i<n-1; i++) {
                if(q[i+1].find(q[i]) == 0) {
                    flag = 0; break;
                }
            }
    
            if(flag) printf("YES\n");
            else printf("NO\n");
        }
    
        return 0;
    }
  • 相关阅读:
    Ubuntu 安装和使用 Supervisor(进程管理)
    Ubuntu查看端口占用及关闭
    Ubuntu 上安装 SQL Server 并创建数据库
    Kafka常用命令
    sql bug
    TiDB之PCTP(数据库专家)
    04 MySQL之函数
    05 MySQL之查询、插入、更新与删除
    03 MySQL之数据类型和运算符
    06 MySQL之索引
  • 原文地址:https://www.cnblogs.com/tanhehe/p/3070194.html
Copyright © 2011-2022 走看看