HDU 1251 统计难题 -- 字典树

1251 ( 统计难题 )
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <time.h>
using namespace std;

const int MAX_26 = 26;
const int MAX_TREE = 390010;
#define FORi_26 for(int i=0;i<MAX_26;i++)
struct TrieTree{
    int ncount;
    char node; // 改名Char
    TrieTree *next[MAX_26]; // 这个指针指向一个地址
}Tt[MAX_TREE];
int tot = 1; // Tt[] array sub

bool Scan(char * str){
    while( *str = getchar() )
        if (*str == '\n'){
            *str = '\0';
            return true;
        }else if (*str == EOF)
            return false;
        else
            str++;
    return true;
}

void UpdataTree(TrieTree *node,char *str){ // 第一次进来的是头结点 
    if (*str == '\0'){
        Tt[0].ncount += 1; // 树种的单词总数
        return ;
    }
    FORi_26{ // 存在前缀往下递归
        TrieTree *temp = node->next[i];
        if ( temp != NULL && temp->node == *str){
            UpdataTree(temp,str+1);
            temp->ncount += 1;
            return ;
        }
    }
    // 不存在前缀往后添一个
    TrieTree *temp = &Tt[tot++]; // 从数组里面 申请一个结点
    FORi_26{
        if (node->next[i] == NULL)
        {    node->next[i] = temp;break;}
    }
    temp->ncount = 1;
    temp->node = *str;
    FORi_26{
        temp->next[i] = NULL;
    }
    UpdataTree(temp,str+1);
}
int SearchTree(TrieTree *node,char *str){
    int res = 0;
    int i=0;
    while(node->next[i] != NULL && *str !='\0'){
        TrieTree *temp = node->next[i];
        if(temp->node == *str){
            res = temp->ncount;
            node = temp; // 下一层
            i = 0;
            str++;
            continue;
        }
        i++;
    }
    if (*str!='\0')
        return 0;
    return res;
}

int main(){

    char str[12];
    while(Scan(str) && str[0] != '\0')
        UpdataTree( &Tt[0] , str );

    //there is a blank enter in the two parts

    while(Scan(str) && str[0] != '\0')
        printf("%d\n", SearchTree( &Tt[0] , str ));

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值