Hdu-5573 Binary Tree(贪心构造)

185 篇文章 0 订阅
65 篇文章 0 订阅
The Old Frog King lives on the root of an infinite tree. According to the law, each node should connect to exactly two nodes on the next level, forming a full binary tree.

Since the king is professional in math, he sets a number to each node. Specifically, the root of the tree, where the King lives, is 1 . Say froot=1 .

And for each node u , labels as fu , the left child is fu×2 and right child is fu×2+1 . The king looks at his tree kingdom, and feels satisfied.

Time flies, and the frog king gets sick. According to the old dark magic, there is a way for the king to live for another N years, only if he could collect exactly N soul gems.

Initially the king has zero soul gems, and he is now at the root. He will walk down, choosing left or right child to continue. Each time at node x , the number at the node is fx (remember froot=1 ), he can choose to increase his number of soul gem by fx , or decrease it by fx .

He will walk from the root, visit exactly K nodes (including the root), and do the increasement or decreasement as told. If at last the number is N , then he will succeed.

Noting as the soul gem is some kind of magic, the number of soul gems the king has could be negative.

Given N , K , help the King find a way to collect exactly N soul gems by visiting exactly K nodes.


题意:给你一个n和k和一颗完全二叉树(权值1 2 3 4 5 6 ...),让你从1开始一直到第k层选择一条路径,路径上的每个点可以选择*1或*(-1),让你输出一种构造方案恰好到第n曾能得到n,


分析:我们注意到可以只用1 2 4 8 ...及最左边数来构造n,将n化为二进制,若倒序第k位为1,那么这一层取 + ,然后抹去最高位的1继续递归,若为0,那么这一次还要取 + (最后一层比前边几层加一块都大),但是剩下的数变成了1<<(k-1) - n继续递归,然后递归完毕后再将前边每一位取反即可,注意这样只能表示奇数,偶数需要特别处理一下。


#include<iostream>
#include<string>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<set>
#include<map>
#include<vector>
#include<cstring>
#include<stack>
#include<cmath>
#include<queue>
#define INF 0x3f3f3f 3f
#define eps 1e-9
#define got(x) (1ll<<x)
using namespace std;
int T,k,f[100];
long long n;
void build(long long n,int k)
{
	f[k] = 1;
	if(k == 1) return;
	if(n & got(k-1)) build(n - got(k-1),k-1);
	else
	{
		build(got(k-1) - n,k-1);
		for(int i = 1;i <= k-1;i++) f[i] *= -1;
	}
}
int main()
{
	scanf("%d",&T);
	for(int t = 1;t <= T;t++)
	{
		scanf("%I64d%d",&n,&k);
		if(n & 1) build(n,k);
		else build(n-1,k);
		cout<<"Case #"<<t<<":"<<endl;
		for(int i = 1;i <= k;i++)
		{
			if(i == k && (n & 1) == 0) cout<<got(i-1)+1<<" ";
			else cout<<got(i-1)<<" ";
			if(f[i] > 0) cout<<"+"<<endl;
			else cout<<"-"<<endl;
		}
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值