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;
    }
  • 相关阅读:
    BCD与ASCII码互转-C语言实现
    <<用法
    linux无锁化编程--__sync_fetch_and_add系列原子操作函数
    C中的volatile用法
    c++ k^1
    linux ftp使用相关
    linux应用程序启动时加载库错误问题
    kafka消费者脚本无法启动问题
    Django框架简介
    前端基础之Bootstrap
  • 原文地址:https://www.cnblogs.com/tanhehe/p/3070194.html
Copyright © 2011-2022 走看看