码迷,mamicode.com
首页 > 其他好文 > 详细

hihoCoder 1014trie树(字典树)

时间:2015-07-27 22:48:39      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

hihoCoder 1014

题目提示已经很清楚了~

贴代码……

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int MAXN = 100000 + 10;
const int alNum = 26;
struct Node{
    int cnt;
    int next[alNum];
    void init(){
        memset(next,-1,sizeof(next));
        cnt = 0;
        return;
    }
};
Node trie[MAXN];
int tt;
void build_trie(char str[]){
    int len = strlen(str);
    int p = 0;
    for(int i = 0;i < len;i++){
        int ch = str[i] - a;
        if(trie[p].next[ch] == -1){
            trie[tt].init();
            trie[p].next[ch] = tt++;
        }
        p = trie[p].next[ch];
        trie[p].cnt++;
    }
}
int quercy(char str[]){
    int len = strlen(str);
    int p = 0;
    for(int i = 0;i < len;i++){
        int ch = str[i] - a;
        if(trie[p].next[ch] == -1){
            return 0;
        }
        p = trie[p].next[ch];
    }
    return trie[p].cnt;
}
int main(){
//    freopen("input.txt","r",stdin);
    int n,m;
    while(~scanf("%d",&n)){
        char str[20];
        tt = 0;
        trie[tt++].init();
        for(int i = 0;i < n;i++){
            scanf("%s",str);
            build_trie(str);
        }
        scanf("%d",&m);
        for(int i = 0;i < m;i++){
            scanf("%s",str);
            int q = quercy(str);
            printf("%d\n",q);
        }
    }
    return 0;
}

hdu1671  Phone List

字典树 水题

判断一个是否为另一个的前缀。

注意 9113

  911 的情况……

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int MAXN = 10000000 + 10;
const int NextNum = 10;

int tt;
struct Node{
    int next[NextNum];
    bool flag;
    void init(){
        memset(next,-1,sizeof(next));
        flag = 0;
    }
};
Node trie[MAXN];
bool build_trie(char str[]){
    int p = 0;
    int len = strlen(str);
    for(int i = 0;i < len;i++){
        int x = str[i] - 0;
        if(trie[p].next[x] == -1){
            trie[tt].init();
            trie[p].next[x] = tt++;
        }
        p = trie[p].next[x];
        if(trie[p].flag){
            return 0;
        }
    }
    for(int i = 0;i < NextNum;i++){
        if(trie[p].next[i] != -1){
            return 0;
        }
    }
    trie[p].flag = 1;
    return 1;
}

int main(){
//    freopen("input.txt","r",stdin);
    int t;
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&n);
        tt = 0;
        trie[tt++].init();
        bool ok = 1;
        char str[40+10];
        for(int i = 0;i < n;i++){
            scanf("%s",str);
            if(!ok){
                continue;
            }
            ok = build_trie(str);
        }
        printf("%s\n",ok?"YES":"NO");
    }
    return 0;
}

 

hihoCoder 1014trie树(字典树)

标签:

原文地址:http://www.cnblogs.com/hanbinggan/p/4681313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!