Subtrees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 344 Accepted Submission(s): 171
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. (1≤N≤1018)
For each case contains a single integer N on a line. (1≤N≤1018)
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;
}