hdu 1251 统计难题 字典树

注意数组大小,字典树比较浪费空间,在统计个数时,不要再结构体中再开26的数组

还有下面更新与统计时,注意与指针pre的先后顺序


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 500000;
struct node{
    int next[26], cnt;
    void ini(){
        memset( next, -1, sizeof( next));
        cnt = 0;         //这里注意,记录不要开成cnt[26]
    }
}tree[maxn];
int main(){
    //freopen("1.txt", "r", stdin);
    char tmp[20];
    int flag = 0;
    int ans, i, j, k, pre = 0, len, aa;
    ans = 1;
    for( i= 0; i<maxn; i++) tree[i].ini();
    while( gets(tmp)){
        len = strlen( tmp);
        if( len == 0 ) flag = 1;
        if( flag == 0){
            pre = 0;
            for( i= 0; i<len; i++){
               aa = tmp[i]- 'a';
                if( tree[pre].next[aa] == -1){
                    tree[pre].next[aa] = ans;
                    pre = ans;
                    ans++;
                }
                else {
                    pre = tree[pre].next[aa];
                }
                tree[pre].cnt ++;
            }
        }
        else{
            pre= 0;
            for( i= 0; i<len; i++){
                aa = tmp[i]- 'a';
                if( tree[pre].next[aa] == -1){
                    printf("0\n");
                    break;
                }
                else {

                    pre = tree[pre].next[aa];
                    if( i== (len - 1)){
                        printf("%d\n", tree[pre].cnt);
                    }
                }
            }
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值