poj 2418 Hardwood Species

map
// 题意:给出不同的树,求每种树所占的比例,并要求树名按字典序由小到大输出
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
map<string,int> col;
char str[100];
double tot=0;
while(gets(str))
{
col[str]++;
tot+=1;
}
for(map<string,int>::iterator ite=col.begin();ite!=col.end();++ite)
{
printf("%s %.4lf\n",(ite->first).c_str(),ite->second*100/tot);
}
return 0;
}

 

 

 

#include <iostream>        //二叉查找树(二叉排序树)
#include <string>

using namespace std;
struct Node
{
char ch[35];
int num; //该结点出现次数
Node *left,*right;

}node[10010];
Node* root;
int cnt;
Node* newNode(char s[])
{
Node* u=&node[++cnt];
strcpy(u->ch,s);
u->num=1;
u->left=u->right=NULL;
return u;
}
void addNode(char s[]) //插入新结点
{

Node *u=root,*fa=root;
int tag;
while(u!=NULL)
{
if(strcmp(s,u->ch)==0) //检测到相同串
{

u->num++;
break;
}
else if(strcmp(s,u->ch)<0) //插入到左子树
{

fa=u; //记录当前结点的父节点
u=u->left;

tag=1;
}
else //插入到右子树
{

fa=u;
u=u->right;
tag=2;
}
}
if(u==NULL) //该串第一次出现
{

if(tag==1)
fa->left=newNode(s);
else
fa->right=newNode(s);
}
}
int tot; //结点总数
void m_order(Node* u) //中序遍历
{

if(u->left)
m_order(u->left);
printf("%s %.4lf\n",u->ch,u->num*100.0/tot);
if(u->right)
m_order(u->right);
}
int main()
{
char s[35];
gets(s);
root=newNode(s);
tot=1;
while(gets(s))
{
addNode(s);
tot++;
}
m_order(root);
return 0;
}



posted on 2012-03-14 22:36  sysu_mjc  阅读(157)  评论(0编辑  收藏  举报

导航