您的位置:首页 > 其它

HUD Problem - 1251 统计难题

2015-08-09 14:20 281 查看
解题感悟:

提交时注意语言选择,这道题用G++提交 ,会爆内存(Memory Limit Exceeded),用c++提交可以AC .

这道题用一般方法(把单词全放在数组里检索)的话一般会超时(Time Limit Exceeded)

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define LOCAL

typedef struct node{
int count;
struct node *next[26];
}tree;

char str[12];
tree root;
int size;

void add_to_tree(char *str);
int sum_num(char *str);

int main(void){

#ifdef LOCAL
freopen("datain.txt","r",stdin);
#endif

size = sizeof(tree);
memset(&root,0,size);
while(gets(str) && str[0]!='\0')
add_to_tree(str);
while(scanf("%s",str)!=EOF)
printf("%d\n",sum_num(str));
return 0;
}
//add the word to the tree;
void add_to_tree(char *str){
int len = strlen(str);
tree *pointer = &root;
pointer->count++;
int i;
for(i=0;i<len;++i){
if(pointer->next[str[i]-'a'] == NULL){
pointer->next[str[i]-'a'] = (tree *)malloc(size);
memset(pointer->next[str[i]-'a'],0,size);
}
pointer = pointer->next[str[i]-'a'];
pointer->count++;
}
}

//find the number of words which contain this prefix;
int sum_num(char *str){
int len=strlen(str);
tree *pointer = &root;
int i;
for(i=0;i<len;++i){
pointer = pointer->next[str[i]-'a'];
if(pointer==NULL)
return 0;
}
return pointer->count;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: