hdu 5524 二叉树找规律,二进制相关

时间:2023-12-21 09:40:32

input

n 1<=n<=1e18

output

有n个结点的满二叉树有多少个不相同结点数的子树

做法:树有h=log2(n)层,最多有2h-2种(1除外),然后再n减去u重复的即可

 #include <bits/stdc++.h>
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <bitset>
#define MAX 100000
#define LL long long
using namespace std;
LL n;
int highbit(LL x)
{
for(int i=;i>=;i--) if(x&(1LL<<i)) return i+;
}
int lowbit(LL x)
{
for(int i=;i<=;i++) if(x&(1LL<<i)) return i;
}
int main()
{
freopen("in","r",stdin);
//scanf("%d",&T);
while(scanf("%lld",&n)==)
{
int h=highbit(n);
LL maxn=(1LL<<h)-;LL mid=maxn-(1LL<<(h->=?h-:));
// printf("%lld:",n);
// printf("h=%d maxn=%lld mid=%lld\n",h,maxn,mid);
if(n==maxn||n==mid) { printf("%d\n",h);continue; }
h+=h-;
if(n<=mid) h--;
h-=lowbit(n-(maxn>>));
printf("%d\n",h);
}
//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
return ;
}