POJ 2418 Hardwood Species (字典树)

来源:互联网 发布:2011年火过的网络歌曲 编辑:程序博客网 时间:2024/06/07 14:11

读入每个单词,然后建字典树,最后dfs一下读出每个单词的个数/总数即可

注意单词可以含有空格,所以建树的时候要从空格开始开一个30的指针数组就可以了

最后提一点,因为poj时间关键所以没有释放内存,对于实际编程这是相当糟糕的。

#include <stdio.h>#include <malloc.h>#include <string.h>struct node{struct node *al[100];int sum;};int count=0;char data[40];void dfs(struct node *now,int len){int i=0;if(now->sum!=0){data[len]=0;printf("%s %.4f\n",data,(double)now->sum/count*100);}for(i=0;i<100;++i){if(now->al[i]!=NULL){data[len]=i+' ';dfs(now->al[i],len+1);}}return;}int main(){char temp[100];int i=0;struct node *head=(struct node *)malloc(sizeof(struct node)),*p=NULL;memset(head,0,sizeof(struct node));while(gets(temp)!=NULL){p=head;for(i=0;temp[i];++i){if(p->al[temp[i]-' ']==NULL){p->al[temp[i]-' ']=(struct node *)malloc(sizeof(struct node));memset(p->al[temp[i]-' '],0,sizeof(struct node));}p=p->al[temp[i]-' '];}++p->sum;++count;}dfs(head,0);}