HDU 5573 Binary Tree(找规律)

时间:2023-12-16 19:33:20

题目链接: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 = ;
typedef long long LL; struct node
{
LL value;
char ch;
};
node rec[MAXN];
void solve(LL p, LL N)
{
int L = ;
while (true) {
if (N < ) {
rec[L].value = p;
rec[L++].ch = '-';
N += p;
p >>= ;
}
else if (N > ) {
rec[L].value = p;
rec[L++].ch = '+';
N -= p;
p >>= ;
}
else return;
}
} int main()
{
int T;
scanf("%d", &T);
for (int cas = ; cas <= T; ++cas) {
LL N;
int K;
scanf("%lld %d", &N, &K);
LL p = (LL)pow(2L, K - ) + ;
if (N & ) --p;
solve(p, N);
printf("Case #%d:\n", cas);
for (int i = K; i >= ; --i) {
printf("%lld %c\n", rec[i].value, rec[i].ch);
}
}
return ;
}