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.
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;
}
}
对于一个满二叉树(完美二叉树),它的不同结点数等于它的最大深度;
对于一个完全非满二叉树,它的不同结点数是它最大的完美二叉树的深度+一块非完美的树对整个树的贡献;
因此我们只需要递归判断最大的完美二叉树 然后计算非满部分对整体的贡献;
因为深度是从0开始计算 所以最后结果+1;
注意数据类型;