HDU 5524 Subtrees(完全二叉树)

Problem Description
There is a complete binary tree with N nodes.The subtree of the node i has Ai nodes.How many distinct numbers are there of Ai?
 

Input
There are multiple test cases, no more than 1000 cases.
For each case contains a single integer N on a line.
 

Output
The output of each case will be a single integer on a line:the number of subtrees that contain different nodes.
 

Sample Input
  
  
5 6 7 8
 

Sample Output
  
  
3 4 3 5

#include <iostream>
#include <string.h>
#include <cmath>
typedef long long ll;

using namespace std;

	
ll n,ans,maxn;
void find(ll x){

	ll depth=0;
	ll r=x,l=x;

	while(2*l<=n){
		
		l*=2;
		depth++;
	}
	
	while(2*r+1<=n){
		r=2*r+1;
	}
	
	if(l<=r) maxn=max(maxn,depth); //判断满二叉树的条件
	else{
		find(2*x);
		find(2*x+1);
		ans++;
	}
	
}

int main(){
	while(cin>>n){
		ans=0;
		maxn=0;
		find(1);
		cout<<ans+maxn+1<<endl;	
	}
}


题意:有一个有n个结点的完全二叉树,判断有多少个不同的结点(所含子结点数不同就为不同结点);

对于一个满二叉树(完美二叉树),它的不同结点数等于它的最大深度;

对于一个完全非满二叉树,它的不同结点数是它最大的完美二叉树的深度+一块非完美的树对整个树的贡献;

因此我们只需要递归判断最大的完美二叉树 然后计算非满部分对整体的贡献;

因为深度是从0开始计算 所以最后结果+1;

注意数据类型;



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值