poj 2418 Hardwood Species(二叉排序树||map迭代器)
题目:http://poj.org/problem?id=2418
二叉排序树:
View Code
1 #include <iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cstdlib> 5 using namespace std; 6 int n=0; 7 typedef struct node 8 { 9 char s[31]; 10 int num; 11 struct node *lchild; 12 struct node *rchild; 13 }btreenode,*btree; 14 void insert(btree *root,char str[]) 15 { 16 btreenode *p=*root,*f; 17 while(p!=NULL) 18 { 19 if(strcmp(p->s,str)==0) 20 { 21 p->num++; 22 return ; 23 } 24 f=p; 25 if(strcmp(str,p->s)<0) 26 p=p->lchild; 27 else 28 p=p->rchild; 29 } 30 p=(btree )malloc(sizeof(btreenode)); 31 p->num=1; 32 strcpy(p->s,str); 33 p->lchild=NULL; 34 p->rchild=NULL; 35 if((*root)==NULL) 36 { 37 (*root)=p; 38 } 39 else 40 { 41 if(strcmp(f->s,str)<0) 42 { 43 f->rchild=p; 44 } 45 else 46 { 47 f->lchild=p; 48 49 } 50 } 51 return ; 52 } 53 void bianli(btree p) 54 { 55 if(p!=NULL) 56 { 57 bianli(p->lchild); 58 printf("%s %.4f\n",p->s,p->num*100.0/n); 59 bianli(p->rchild); 60 } 61 return ; 62 } 63 int main() 64 { 65 btree root; 66 char str[31]; 67 root=NULL; 68 while(gets(str)!=NULL) 69 { 70 n++; 71 insert(&root,str); 72 } 73 bianli(root); 74 return 0; 75 }
map迭代器:
View Code
1 #include <iostream> 2 #include<string> 3 #include<map> 4 #include<iterator> 5 #include<cstdio> 6 using namespace std; 7 8 int main() 9 { 10 string str; 11 int sum=0; 12 map<string,int>tree; 13 while(getline(cin,str)) 14 { 15 tree[str]++; 16 sum++; 17 } 18 map<string,int>::iterator iter; 19 for(iter=tree.begin();iter!=tree.end();iter++) 20 { 21 cout<<iter->first; 22 printf(" %.4f\n",iter->second*100.0/sum); 23 } 24 return 0; 25 }