poj2418字典树
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef struct AVLTree
{
char name[31];
int cnt;
struct AVLTree *pLeft;
struct AVLTree *pRight;
int nHeight;
}AVLTree;
int n=0;
int Height(AVLTree * pNode)
{
if(pNode==NULL) return -1;
return pNode->nHeight;
}
AVLTree * LLRotate(AVLTree *pNode)
{
AVLTree *pNode1;
pNode1=pNode->pLeft;
pNode->pLeft = pNode1->pRight;
pNode1->pRight=pNode;
pNode->nHeight=max(Height(pNode->pLeft),Height(pNode->pRight))+1;
pNode1->nHeight=max(Height(pNode1->pLeft),pNode->nHeight)+1;
return pNode1;
}
AVLTree *RRRotate(AVLTree * pNode)
{
AVLTree *pNode1;
pNode1=pNode->pRight;
pNode->pRight=pNode1->pLeft;
pNode1->pLeft=pNode;
pNode->nHeight=max(Height(pNode->pLeft),Height(pNode->pRight))+1;
pNode1->nHeight=max(pNode->nHeight,Height(pNode1->pRight))+1;
return pNode1;
}
AVLTree * RLRotate(AVLTree * pNode)
{
pNode->pRight =LLRotate(pNode->pRight);
return RRRotate(pNode);
}
AVLTree *LRRotate(AVLTree *pNode)
{
pNode->pLeft=RRRotate(pNode->pLeft);
return LLRotate(pNode);
}
AVLTree * _Insert(char *s,AVLTree *pNode)
{
if(pNode==NULL)
{
pNode =(AVLTree *) malloc(sizeof (AVLTree));
strcpy(pNode->name,s);
pNode->pLeft=pNode->pRight =NULL;
pNode->cnt=1;
pNode->nHeight =0;
}
else if(strcmp(pNode->name,s)<0)
{
pNode->pRight=_Insert(s,pNode->pRight);
if(Height(pNode->pRight)-Height(pNode->pLeft)==2)
{
if(strcmp(s,pNode->name)>0)
pNode=RRRotate(pNode);
else pNode =RLRotate(pNode);
}
}
else if(strcmp(pNode->name,s)>0)
{
pNode->pLeft=_Insert(s,pNode->pLeft);
if(Height(pNode->pLeft)-Height(pNode->pRight)==2)
{
if(strcmp(s,pNode->name)>0)
pNode=LRRotate(pNode);
else pNode=LLRotate(pNode);
}
}
else pNode->cnt++;
pNode->nHeight=max(Height(pNode->pLeft),Height(pNode->pRight))+1;
return pNode;
}
void mid_cal(AVLTree * pRoot)
{
if(pRoot!=NULL)
{
mid_cal(pRoot->pLeft);
printf("%s %.4f\n",pRoot->name,100.0*pRoot->cnt/n);
mid_cal(pRoot->pRight);
}
}
int main()
{
AVLTree *pRoot=NULL;
char s[31];
while(gets(s)!=NULL)
{
// puts("---------------------------");
//if(strcmp(s,"null")==0) break;
pRoot=_Insert(s,pRoot);
n++;
} mid_cal(pRoot);
// printf("%d\n",n);
return 0;
}