POJ 2418 Hardwood Species
这个题可以用多种方法解决。
题目大意:
就是输入一堆字符串,可能重复,按字典序输出,并输出占的比例。
可以用字典树,二叉查找树,Map,快排等等多种方法。
我用的二叉查找树,下面是代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> struct node { int cut; char c[40]; struct node *l,*r; } head; char s[40]; double f,cut; void build() { struct node *p,*q; p=&head; while(1) { if(strcmp(p->c,s)>0) { if(p->r==NULL) { q=(struct node *)malloc(sizeof(struct node)); strcpy(q->c,s); q->cut=1; q->l=NULL; q->r=NULL; p->r=q; return ; } p=p->r; } else if(strcmp(p->c,s)==0) { p->cut++; return ; } else { if(p->l==NULL) { q=(struct node *)malloc(sizeof(struct node)); strcpy(q->c,s); q->cut=1; q->l=NULL; q->r=NULL; p->l=q; return ; } p=p->l; } } } void pr(struct node *p) { if(p==NULL) { return; } pr(p->r); f=p->cut; printf("%s %.4f\n",p->c,(f*100.00)/cut); pr(p->l); } int main() { int flat=1; cut=0; while(gets(s)) { if(flat) { strcpy(head.c,s); head.cut=1; head.l=NULL; head.r=NULL; flat=0; } else { build(); } cut++; } pr(&head); return 0; }