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());
}
}
对与当前的树的左右子树结点数的计算 可以先计算出最后一层有多少个结点 (预处理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());
}
}
相关文章推荐
- 单链表的程序实现
- 配置eclipse开发floodlight环境
- 图像复原
- Android打包安装过程
- 发声控制
- bootstrap学习1
- salt-master IPC文件的一次报错
- ubuntu 14.04 安装mysql
- win7系统瘦身方法,C盘瘦身方法
- FZU-Problem 2191 完美的数字
- iOS本地通知和远程通知
- 16.UISwitch(开/关视图)
- C++编程规范---读书有感(1)
- swift学习笔记->函数
- 如何接入学历查询接口(附代码)
- Django卸载重新安装
- Cocos2D:塔防游戏制作之旅(一)
- Move Zeroes
- Cocos2D:塔防游戏制作之旅(一)
- Cocos2D:塔防游戏制作之旅(一)