hdu - 1251 - 统计难题(Trip)

题意:Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

——>>叫统计难题,其实是。。。偷笑。。。

只需组织好Trip,并保存每个结点被单词经过的次数。。。询问时沿着Trip走就是。。。

#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

const int maxw = 10 + 5;

char name[maxw], pre[maxw];

struct node{
    int cnt;
    node *next[26];
    node(){
        cnt = 0;
        memset(next, 0, sizeof(next));
    }
};

struct Trip{
    node *root;

    Trip(){
        root = new node;
    }

    int idx(char c){
        return c - 'a';
    }

    void insert(char *s){
        int len = strlen(s), i;
        node *t = root;
        for(i = 0; i < len; i++){
            int c = idx(s[i]);
            if(!t->next[c]) t->next[c] = new node;
            t->next[c]->cnt++;
            t = t->next[c];
        }
    }

    void solve(char *s){
        int ret = -1;
        node *t = root;
        int len = strlen(s);
        for(int i = 0; i < len; i++){
            int c = idx(s[i]);
            t = t->next[c];
            if(!t){
                ret = 0;
                break;
            }
        }
        if(ret == -1) ret = t->cnt;
        printf("%d\n", ret);
    }
};

int main()
{
    Trip trip;
    while(gets(name)){
        if(!strlen(name)) break;
        trip.insert(name);
    }
    while(scanf("%s", pre) == 1){
        trip.solve(pre);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值