您的位置:首页 > 其它

hdu 1251 统计难题

2017-09-21 22:14 316 查看
题目:点击打开链接

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

代码:

///#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对结构体内的元素赋值要特别注意!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: