• hihocoder 1014 Trie树


      题目链接:http://hihocoder.com/problemset/problem/1014 ,刚学的字典树,就当模板了。

      最近都没有好好刷题,罪过罪过。

    #include <iostream>
    #include <cstdio>
    #include <vector>
    #include <queue>
    #include <stack>
    #include <cmath>
    #include <string>
    #include <string.h>
    #include <algorithm>
    using namespace std;
    #define LL long long
    const int maxn = 1000000;
    struct Trie {
        int ch[maxn][26];
        int cnt[maxn];
        int size;
        Trie() {    
            size = 1; 
            memset(ch[0] , 0 , sizeof(ch[0]));
            memset(cnt , 0 , sizeof(cnt));
        }
        int index(char c) {    return c - 'a';    }
        void insert(char *s , int v) {
            int i , u;
            for(i = u = 0 ; s[i] != '' ; i++) {
                int c = index(s[i]);
                if(!ch[u][c]) { 
                    memset(ch[size] , 0 , sizeof(ch[size]));
                    ch[u][c] = size++;
                }
                u = ch[u][c];
                cnt[u]++;        //必须在这里
            }
        }
        int query(char *s) {
            int i , u;
            for(i = u = 0 ; s[i] != '' ; i++) {
                int c = index(s[i]);
                if(!ch[u][c])        return 0;
                u = ch[u][c];
            }
            return cnt[u];
        }
    } trie;
    
    int main() 
    {
        int n , m;
        char s[20];
        scanf("%d" , &n);
        while(n--) {
            scanf("%s" , s);
            trie.insert(s , 1);
        }
        scanf("%d" , &m);
        while(m--) {
            scanf("%s" , s);
            printf("%d
    " , trie.query(s));
        }
    }
  • 相关阅读:
    API和String
    集合
    类和对象
    多态
    内部类
    继承
    抽象类
    常用API
    包和修饰符
    异常
  • 原文地址:https://www.cnblogs.com/H-Vking/p/4467754.html
Copyright © 2020-2023  润新知