poj 2418 Hardwood Species

// 题意:给出不同的树,求每种树所占的比例,并要求树名按字典序由小到大输出
#include <iostream> //map
#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++;
}
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;
}



#include <iostream> // trie树
using namespace std ;
struct Node
{
int next[95];
int num; //记录该节点所代表的字符串出现的次数
}table[300000];
int cur;
void init()
{
memset(table[0].next,-1,sizeof(table[0].next));
cur=1;
}
void insert(char ch[])
{
Node* p=&table[0];
for(int i=0;ch[i];++i)
{
int j=ch[i]-' ';
if(p->next[j]==-1)
{
p->next[j]=cur++;
Node* q=&table[p->next[j]];
for(int k=0;k<95;++k)
q->next[k]=-1;
q->num=0; //该节点所代表的字符串一定还没出现过
}
p=&table[p->next[j]];
}
p->num++; //该字符串出现的次数+1
}
int tot;
void dfs(int pos,char ch[],int rear)
{
Node* p=&table[pos];
if( p->num > 0 )
{
for(int i=0;i<rear;++i)
printf("%c",ch[i]);
printf(" %.4lf\n",p->num*100.0/tot);
}
for(int i=0;i<95;++i)
{
if(p->next[i]!=-1)
{
ch[rear]=i+' ';
dfs(p->next[i],ch,rear+1);
}
}
}
int main()
{
init();
char s[35];
while(gets(s))
{
insert(s);
tot++;
}
dfs(0,s,0);
return 0;
}

posted on 2012-03-28 17:30  sysu_mjc  阅读(321)  评论(0编辑  收藏  举报

导航