poj 2418 Hardwood Species

本文介绍了一种使用AVL树数据结构来统计文本中各个单词出现频率的方法。通过不断插入新单词并更新现有单词计数的方式,该程序能够维持树的平衡,并最终输出每个单词及其占总单词数的比例。

        统计每个单词出现的频率。这题可以用各种数据结构做,作为练习,又敲了一个AVL树。


#include <iostream>    
#include <stdio.h>    
#include <string>    
#include <map>    
#include <vector>    
#include <stack>    
#include <queue>    
#include <string.h>    
#include <algorithm>    
#include <math.h>    
    
using namespace std;    

char str[32];
struct avl{
	char data[32];
	int height;
	avl* pleft;
	avl* pright;
	int size;
	int cnt;
};

int Height(avl* pNode){
	if(NULL==pNode)return -1;
	return pNode->height;
}


avl* LLRotate(avl* pNode){
	avl* l=pNode->pleft;
	pNode->pleft=l->pright;
	l->pright=pNode;
	pNode->height=max(Height(pNode->pleft),Height(pNode->pright))+1;
	l->height=max(Height(l->pleft),Height(l->pright))+1;
	return l;
}

avl* RRRotate(avl* pNode){
	avl* r=pNode->pright;
	pNode->pright=r->pleft;
	r->pleft=pNode;
	pNode->height=max(Height(pNode->pleft),Height(pNode->pright))+1;
	r->height=max(Height(r->pleft),Height(r->pright))+1;
	return r;
}

avl* LRRotate(avl* pNode){
	pNode->pleft=RRRotate(pNode->pleft);
	return LLRotate(pNode);
}

avl* RLRotate(avl* pNode){
	pNode->pright=LLRotate(pNode->pright);
	return RRRotate(pNode);
}

avl* insert(avl* pNode,char* data){
	if(pNode==NULL){
		pNode=new avl();
		memcpy(pNode->data,data,sizeof(str));
		pNode->height=0;
		pNode->size=1;
		pNode->cnt=1;
		pNode->height=max(Height(pNode->pleft),Height(pNode->pright));
		return pNode;
	}
	
	int cmp=strcmp(data,pNode->data);
	
	if(cmp<0){
		pNode->pleft=insert(pNode->pleft,data);
		pNode->size++;
		if(Height(pNode->pleft)-Height(pNode->pright)==2){	//不平衡 
			if(data<pNode->pleft->data){
				pNode=LLRotate(pNode);
			}else{
				pNode=LRRotate(pNode);
			}
		}
	}else if(cmp>0){
		pNode->pright=insert(pNode->pright,data);
		pNode->size++;
		if(Height(pNode->pright)-Height(pNode->pleft)==2){	//不平衡 
			if(data>pNode->pright->data){
				pNode=RRRotate(pNode);
			}else{
				pNode=RLRotate(pNode);
			}
		}
	}else{
		pNode->cnt++;
	}
	pNode->height=max(Height(pNode->pleft),Height(pNode->pright));
	return pNode;
}
int tot;
void print(avl* pNode){
	if(pNode->pleft){
		print(pNode->pleft);
	}
	printf("%s %.4lf\n",pNode->data,pNode->cnt*100.0/tot );
	if(pNode->pright){
		print(pNode->pright);
	}
}


int main(){
	tot=0;
	
	avl* root=NULL;
	while(gets(str)){
		root=insert(root,str);
		tot++;
	}
	print(root);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值