HDU 1251 统计难题

18 篇文章 0 订阅
2 篇文章 0 订阅
  • 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
  • 题意:输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串。输出以该字符串为前缀的单词个数。
    • 注意:本题只有一组测试数据,处理到文件结束.
  • 算法:字典树

#include <bits/stdc++.h>
#define pi acos(-1)
#define fastio ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const int maxn = 400000 + 10;
const int mod = 1e9 + 7;

char word[20];
int sz=1;

struct node
{
    int child[30];
    int f;
    int hcnt;
    int acnt;
    node(){
        f = 0;
        hcnt = 0;
        acnt = 0;
        memset(child, 0, sizeof(child));
    }
}Trie[maxn];

void _insert(char *s)
{
    int u=0, len = strlen(s), pos;
    for(int i=0; i<len ; i++){
        pos = s[i] - 'a';
        if(Trie[u].child[pos] == 0) { Trie[u].child[pos] = sz++; }
        u = Trie[u].child[pos];
        Trie[u].hcnt++;
    }
    Trie[u].f = 1;
    Trie[u].acnt++;
}

int _find(char *s)
{
    int u=0, len = strlen(s), pos;
    for(int i=0; i<len; i++){
        pos = s[i] - 'a';
        if(Trie[u].child[pos] == 0){ return 0; }
        u = Trie[u].child[pos];
    }
    return Trie[u].hcnt;
}

int main()
{
    while(cin.getline(word, 15)){
        if(strlen(word) == 0) break;
        else _insert(word);
    }
    //printf("啦啦啦啦\n");
    while(cin.getline(word, 15)){
        printf("%d\n", _find(word));
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值