您的位置:首页 > 其它

HDU 5524 Subtrees

2015-11-16 20:29 239 查看
由于要求一颗完全二叉树的子树的种类数 因为一棵完全二叉树当结点数已知时树的形状是固定的 所以可以通过递归去做 将n放进set之后 处理出n所对应的完全二叉树的左右子树的数目 递归访问即可 同时采用记忆化搜索的方式 如果set中已经存在改数 就不在访问 这样复杂度接近log2(n)²

对与当前的树的左右子树结点数的计算 可以先计算出最后一层有多少个结点 (预处理k层的满二叉树的结点数 二分查找 减去即可) 然后把最后一层大于上一层的数目分给右子树 左子树用(总-1-右)即可

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cctype>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
#include<set>
#define scnaf scanf
#define cahr char
#define bug puts("=========================");
using namespace std;
typedef long long ll;
const int maxn=3000+5;
const int mod=1000000007;
set<ll>st;
ll n;
ll a[200];
ll b[200];
int cnt=0;
void init()
{
ll z=1;
ll N=3e18;
for(int i=0; z<=N; i++,cnt++)
{
a[i]=z-1;
b[i]=z/2;
z*=2;
}
}
void dfs(ll n)
{
if(n==1) return;
int id=lower_bound(a,a+cnt,n)-a;
ll nn=n-a[id-1];
ll right=a[id-2]+max((ll)0,nn-b[id-1]);
ll left=n-right-1;
if(left>0&&st.count(left)==0)
{
st.insert(left);
dfs(left);
}
if(right>0&&st.count(right)==0)
{
st.insert(right);
dfs(right);
}
}
int main()
{
init();
while(~scanf("%I64d",&n))
{

st.clear();
st.insert(n);
dfs(n);
st.insert(1);
printf("%d\n",st.size());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: