hdu 1251 统计难题

题目:点击打开链接

分析:一道裸的字典树模板题。。。

代码:

///#include<bits/stdc++.h>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn = 1e5;
struct tre{
    int next[26];
    int val;
}tree[5*maxn];
int cnt=1;

int init(){///初始化节点
    memset(&tree[cnt],0,sizeof(tre));///把next数组和val都赋值为0(结构体节点整体赋值)
    return cnt++;
}

void build(char *s){
    int tmp=0,len=strlen(s);
    for(int i=0;i<len;i++){
        int num=s[i]-'a';
        if(!tree[tmp].next[num])
            tree[tmp].next[num]=init();
        tmp=tree[tmp].next[num];
        tree[tmp].val++;///每个字符串的所有前缀标记+1
    }
}

int Count(char *s){///记录前缀所含个数
    int index=0,len=strlen(s);
    for(int i=0;i<len;i++){
        int num=s[i]-'a';
        if(!tree[index].next[num]) return 0;
        index=tree[index].next[num];
    }
    return tree[index].val;
}

int main(){
    memset(&tree[0],0,sizeof(tre));
    char word[11];
    
//    while(gets(word)){
//         if(word[0]==NULL)    //空行。gets读入的回车符会自动转换为NULL。
//             break;
//         Insert(word);
//    }
//    while(gets(word)){
//         if(word[0]==NULL)    //空行。gets读入的回车符会自动转换为NULL。
//             break;
//         Insert(word);
//    }
    
    while(cin.getline(word,12)){    ///输入单词
        if(strlen(word)==0 || word[0]==' ')    ///如果读入字符串的长度为0或者是空格,说明读入的是空行
            break;
        build(word);
     }
     while(scanf("%s",word)!=EOF)
         cout<<Count(word)<<endl;
}

这次被memset函数坑了。。。  memset是以字节为单位,初始化内存块,memset函数一共有三个参数,第一个是变量的地址,第二是所赋的值,int数组只能为0或-1,第三个为内存块的大小。memset对结构体内的元素赋值要特别注意!!!


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值