Description
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
. Say
.
And for each node
, labels as
, the left child is
and right child is
. 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
years, only if he could collect exactly
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
, the number at the node is
(remember
), he can choose to increase his number of soul gem by
, or decrease it by
.
He will walk from the root, visit exactly
nodes (including the root), and do the increasement or decreasement as told. If at last the number is
, 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
,
, help the King find a way to collect exactly
soul gems by visiting exactly
nodes.
Input
, which indicates the number of test cases.
Every test case contains two integers
and
, which indicates soul gems the frog king want to collect and number of nodes he can visit.
.
.
.
Output
Case #x:
” first, where
indicates the case number and counts from
.
Then
lines follows, each line is formated as ‘a b’, where
is node label of the node the frog visited, and
is either ‘+’ or ‘-‘ which means he increases / decreases his number by
.
It’s guaranteed that there are at least one solution and if there are more than one solutions, you can output any of them.
Sample Input
2 5 3 10 4
Sample Output
Case #1: 1 + 3 - 7 + Case #2: 1 + 3 + 6 - 12 +
/* 想到了贪心没想到二进制优化,贪了几发GG; 完全二叉树左边节点1 2 4 8 ......到k层位置和为2^k-1,但n最大为2^k只需要将叶子向右移一位就可以了 这个不同于二进制构造,减去相当于对总值作用了 2*2^k 所以要减去的和为 d=2^k-1-n,用二进制构造出d然后减去构造d的数,其它数都加上就行了 */ #include<bits/stdc++.h> using namespace std; int n,k; int vis[65]; int bit[64]; int main() { //freopen("C:\\Users\\acer\\Desktop\\in.txt","r",stdin); int T; int cas =1; scanf("%d",&T); while(T--) { memset(vis,0,sizeof vis); memset(bit,0,sizeof bit); printf("Case #%d:\n",cas++); scanf("%d%d",&n,&k); long long d=(1<<k)-1; d-=n; if(d%2) d++; d/=2;//需要减去的数字 for(int i=1;i<64;i++) { bit[i]=d%2; d/=2; } long long s=0; int cur=1; for(int i=1;i<k;i++) { printf("%d ",cur); if(bit[i]) { s-=cur; printf("-\n"); } else { s+=cur; printf("+\n"); } cur*=2; } if(s+cur==n) printf("%d +\n",cur); else printf("%d +\n",cur+1); } return 0; }
转载于:https://www.cnblogs.com/wuwangchuxin0924/p/6044884.html