您的位置:首页 > 其它

【规律】【贪心】【数学】HDU 5573 Binary Tree

2016-05-18 13:45 281 查看
[b]题目链接:[/b]

  http://acm.hdu.edu.cn/showproblem.php?pid=5573


[b]题目大意:[/b]

  从1走到第k层,下一层的数是上一层的数*2或者*2+1,可以选择加上或者减去走的数,最终要求结果为n

  输出每层走的数,和是加还是减

[b]题目思路:[/b]

  【规律】【贪心】【数学】

  首先苦思冥想一下,发现,1 2 4 8...2k可以凑成任意的奇数。而偶数只需要把2k变为2k+1。

  (从k往1位考虑加减,把+看为1,-看为0,则1+2+4+...=2k-1,符号可以用二进制数X表示,为1111111...,每次X-1,则原式的答案-2)

  (如+1+2+4+8=24-1=15,X=1111,则当X=1110时,表示-1+2+4+8=13,X=1101时,表示+1-2+4+8=11,以此类推可以得到任意奇数,偶数同理)

  所以可以从2k往前推,当前值比n大就去-,小就取+。

//
//by coolxxx
//
#include<iostream>
#include<algorithm>
#include<string>
#include<iomanip>
#include<memory.h>
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
#include<math.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define abs(a) ((a)>0?(a):(-(a)))
#define lowbit(a) (a&(-a))
#define sqr(a) ((a)*(a))
#define swap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))
#define eps 1e-8
#define J 10
#define MAX 0x7f7f7f7f
#define PI 3.1415926535897
#define N 77
using namespace std;
int cas,cass;
long long n,m,lll,ans;
long long e
;
void print(int top,int x)
{
if(top==0)
{
if(x<n)puts("1 +");
else puts("1 -");
return;
}
if(x>n)
{
print(top-1,x-e[top]);
printf("%lld -\n",e[top]);
}
else
{
print(top-1,x+e[top]);
printf("%lld +\n",e[top]);
}
}
int main()
{
#ifndef ONLINE_JUDGE
//    freopen("1.txt","r",stdin);
//    freopen("2.txt","w",stdout);
#endif
int i,j,k;
//    while(~scanf("%s",s1))
//    while(~scanf("%d",&n))
for(e[0]=1,i=1;i<=61;i++)
e[i]=e[i-1]<<1;
for(scanf("%d",&cas),cass=1;cass<=cas;cass++)
{
printf("Case #%d:\n",cass);
scanf("%lld%lld",&n,&m);
m--;
if(n&1)
{
print(m-1,e[m]);
printf("%lld +\n",e[m]);
}
else
{
print(m-1,e[m]+1);
printf("%lld +\n",e[m]+1);
}
}
return 0;
}

/*
//

//
*/


千万不要点
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: