//poj 2418 Hardwood Species(AVL树(平衡二叉树)+中序遍历=>排序)
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
struct AVLtree
{
char name[33];
int count;
int nheight;
struct AVLtree *pleft;
struct AVLtree *pright;
};
int n;
int Max(int a,int b)
{
return a>b?a:b;
}
int Height(AVLtree *pnode)
{
if(NULL==pnode)
{
return -1;
}
return pnode->nheight;
}
AVLtree *LLRotate(AVLtree *pnode)
{
/*=======================================
pnode pnode->pleft
/ / \
pnode->pleft ==> / \
/ / pnode
pnode->pleft->pleft pnode->pleft->pleft
=========================================*/
AVLtree *p;
p=pnode->pleft;
pnode->pleft=p->pright;
p->pright=pnode;
pnode->nheight=Max(Height(pnode->pleft),Height(pnode->pright))+1;
p->nheight=Max(Height(p->pleft),pnode->nheight)+1;
return p;
}
AVLtree *RRRotate(AVLtree *pnode)
{
/*=======================================
pnode pnode->pleft
\ / \
pnode->pleft ==> / \
\ / pnode->pleft->pleft
pnode->pleft->pleft pnode
=========================================*/
AVLtree *p;
p=pnode->pright;
pnode->pright=p->pleft;
p->pleft=pnode;
pnode->nheight=Max(Height(pnode->pleft),Height(pnode->pright))+1;
p->nheight=Max(Height(p->pright),pnode->nheight)+1;
return p;
}
AVLtree *LRRotate(AVLtree *pnode)
{
/*=======================================
pnode pnode pnode->pleft
/ / / \
pnode->pleft pnode->pleft ==> / \
\ / / pnode
pnode->pleft->pleft pnode->pleft->pleft pnode->pleft->pleft
=========================================*/
pnode->pleft=RRRotate(pnode->pleft);
return LLRotate(pnode);
}
AVLtree *RLRotate(AVLtree *pnode)
{
/*=======================================
pnode pnode pnode->pleft
\ / / \
pnode->pleft pnode->pleft ==> / \
/ / / pnode
pnode->pleft->pleft pnode->pleft->pleft pnode->pleft->pleft
=========================================*/
pnode->pright=LLRotate(pnode->pright);
return RRRotate(pnode);
}
AVLtree *_insert(char *s,AVLtree *pnode)
{
if(NULL==pnode)
{
pnode=new AVLtree;
strcpy(pnode->name,s);
pnode->pleft=NULL;
pnode->pright=NULL;
pnode->count=1;
pnode->nheight=0;
}
else if(strcmp(s,(pnode)->name)==0)
{
pnode->count++;
}
else if(strcmp(s,(pnode)->name)<0)
{
pnode->pleft=_insert(s,pnode->pleft);
if(Height(pnode->pleft)-Height(pnode->pright)==2)
{
if(strcmp(s,pnode->pleft->name)<0)
{
pnode=LLRotate(pnode);
}
else
{
pnode=LRRotate(pnode);
}
}
}
else
{
pnode->pright=_insert(s,pnode->pright);
if(Height(pnode->pleft)-Height(pnode->pright)==-2)
{
if(strcmp(s,pnode->pright->name)>0)
{
pnode=RRRotate(pnode);
}
else
{
pnode=RLRotate(pnode);
}
}
}
pnode->nheight=Max(Height(pnode->pleft),Height(pnode->pright))+1;
return pnode;
}
void mid_cal(AVLtree *root)
{
if(root!=NULL)
{
mid_cal(root->pleft);
printf("%s %0.4lf\n",root->name,((double)(root->count)/(double)n)*100);
mid_cal(root->pright);
}
}
int main()
{
freopen("pj2418.in","r",stdin);
AVLtree *root=NULL;
char s[33];
while(gets(s)!=NULL)
{
root=_insert(s,root);
n++;
}
mid_cal(root);
return 0;
}
poj2418 Hardwood Species(AVL树(平衡二叉树)中序遍历=排序)
最新推荐文章于 2024-09-28 17:58:38 发布