您的位置:首页 > 其它

HDU 5573 Binary Tree(找规律)

2015-12-02 10:27 399 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5573

题意:给你一个完全二叉树,节点为自然数的排列(第一行1,第二行2 3,第三行4 5 6 7。。。)。现在,给你一个N和K,K表示给你这个完全二叉树的前K行,从第1行到第K行有很多路径,希望找到一条路径能表示N,路径上的节点可取正也可取负,要求最后的和为N。

思路:由题目给的数据范围可知前两个节点有一个一定可以表示N。(前两个节点可以表示1 - 2^k)

code:

#include <cstdio>
#include <cmath>
using namespace std;
const int MAXN = 65;
typedef long long LL;

struct node
{
LL value;
char ch;
};
node rec[MAXN];
void solve(LL p, LL N)
{
int L = 1;
while (true) {
if (N < 0) {
rec[L].value = p;
rec[L++].ch = '-';
N += p;
p >>= 1;
}
else if (N > 0) {
rec[L].value = p;
rec[L++].ch = '+';
N -= p;
p >>= 1;
}
else return;
}
}

int main()
{
int T;
scanf("%d", &T);
for (int cas = 1; cas <= T; ++cas) {
LL N;
int K;
scanf("%lld %d", &N, &K);
LL p = (LL)pow(2L, K - 1) + 1;
if (N & 1) --p;
solve(p, N);
printf("Case #%d:\n", cas);
for (int i = K; i >= 1; --i) {
printf("%lld %c\n", rec[i].value, rec[i].ch);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: