hdu5224Subtrees(递归,好题)

Subtrees

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 344    Accepted Submission(s): 171



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. (1N1018)
 

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
 

Source
 
分析可知,一棵完全二叉树一定是由一棵满的左或者右二叉树加上另外一边
所以我们只需要记录满的二叉树的最大深度,然后递归处理另外一棵未满的二叉树(如果都是满的,直接退出)
递归另外一棵二叉树的时候,碰到根就+1,因为这个根(除了开头的根)一定是另外一棵不慢的二叉树,节点数目肯定和满的二叉树是不同的
#include<bits/stdc++.h>
using namespace std;
__int64 tot[66];
set<int>st;
int ans;

void dfs(__int64 n){
    if(n==0)
        return ;
    n--;
    if(n==0){
        st.insert(1);
        return ;
    }
    ans++;//不是完全二叉树或为根的时候,总数+1
    int i;
    for(i=0;i<64;i++){
        if(tot[i]+tot[i+1]>n)
            break;
    }
    st.insert(i);//最多有几层是完全二叉树
    if(tot[i]+tot[i]==n||tot[i]+tot[i-1]==n)//由两课完全二叉树构成
        return ;
    else
        dfs(n-tot[i]);//去掉另外一个二叉树的1/2
}

int main(){
    __int64 n;
    __int64 S=1;
    for(int i=0;i<=64;i++){
        tot[i]=S-1;
        S*=2;
    }
    while(scanf("%I64d",&n)!=EOF){
        ans=0;
        st.clear();
        dfs(n);
        if(st.begin()!=st.end()){
            ans+=*(st.rbegin());
        }
        printf("%d\n",ans);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值