hdu 1251 统计难题 Trie树

Problem:
给定一个单词表,再每给一个字符串,就输出它作为前缀的最多次数。
Solution:
标准的字典树模板题;
note:
c++比g++更节省内存,c++A了,但是g++没A。

#include<cstdio>
#include<iostream>
#include<sstream>
#include<cstdlib>
#include<cmath>
#include<cctype>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<ctime>
#include<vector>
#include<fstream>
#include<list>
using namespace std;

#define ms(s) memset(s,0,sizeof(s))
typedef unsigned long long ULL;
typedef long long LL;

const double PI = 3.141592653589;
const int INF = 0x3fffffff;

struct node{
    node* next[26];  int v;
    node(){
        v = 1;
        for(int i = 0; i < 26; ++i)
            next[i] = NULL;
    }
};

struct Trie{
    node* root;
    Trie(){root = NULL;}

    void inserts(char str[]){
        int len = strlen(str);
        if(!root)
            root = new node;
        node* now = root;
        for(int i = 0; i < len; ++i){
            int num = str[i]-'a';
            if(now->next[num] == NULL)
                now->next[num] = new node;
            else
                ++((now->next[num])->v);
            now = now->next[num];
        }
    }

    int searchs(char str[]){
        int len = strlen(str);
        node* now = root;
        for(int i = 0; i < len; ++i){
            int num = str[i]-'a';
            if(now->next[num] == NULL)
                return 0;
            now = now->next[num];
        }
        return now->v;
    }
};

int main(){
//    freopen("E:\\input.txt","r",stdin);
//    freopen("E:\\output.txt","w",stdout);
//    ios::sync_with_stdio(false);
    Trie a;
    int ans;

    char str[20];
    while(gets(str)){
        if(str[0] == '\0')
            break;
        a.inserts(str);
    }
    while(gets(str)){
        ans = a.searchs(str);
        printf("%d\n",ans);
    }



    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值