Eva's Balance
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 3435 | Accepted: 1720 |
Description
Eva has a balance with 20 poises. The weights of the poises are 1, 3, 9, 27,...,3^19. Eva asserts that she has a way to measure any object whose weight is an integer from 1 to (3^20-1)/2. Assuming that Eva has placed an object with the weight in this range on the left tray of the balance, your task is to place the proper poises on the proper trays so as to weigh the object out.
Input
The first line is an integer T (1 <= T <= 20), which shows the number of the test cases. Each of the following T lines contains an integer W (1 <= W <= (3^20-1)/2), expressing the weight of an object.
Output
For each test case print a line, showing the weights of the poises on the left tray and the right tray. Use a space to separate the left tray and the right tray. The poises on the same tray are arranged in the increasing order, and a comma separates every two of them. If there is no poise on the tray, output "empty".
Sample Input
3 9 5 20
Sample Output
empty 9 1,3 9 1,9 3,27
Source
题目描述:你有1, 3, 9。。。一直到3的19次方,有这20个重量的砝码,现在给你一个天平和一个标有重量物体,物体一开始放在天平的左边,让你用这20个砝码中的几个放在天平上,使左右平衡,输出天平左边和右边的详细砝码信息。(已知问题有解)
此题可以转化为3进制的问题,例如物品重为20, 20 = 202(3进制) = 2 * 3^2 + 2 * 3^0 = 2 * 9 + 2
可以写成 20 = 1 -1 1 -1 = 1 * 3^3 - 1 * 3^2 + 1 * 3^1 - 1 * 3^0 = 27 - 9 + 3 - 1
把负的部分移到等号左边:
20 + 9 + 1 = 27 + 3
得到答案:左边放1和9,右边放3 和 27.
那么,怎样将标准的三进制转化成-1 0 1这三个数为系数的“三进制”呢?
从低位到高位的顺序开始:
1:如果当前位为2, 则当前位变为-1(减三), 高一位的系数+1。
//这个是符合的,因为高位的基数是低位的三倍,正好差三。
2:如果当前位是3,则当前位变为0(减三), 高一位的系数+1.道理同上。
3:其他不变。
代码:
#include<iostream>
#include<string>
using namespace std;
char str[1000];
int len;
void judge(int x)
{
while(x / 3)
{
str[len++] = x % 3 + '0';
x /= 3;
}
str[len++] = x + '0';
}
__int64 xx[20];
void out()
{
for(int i = len - 1; i >= 0; i--)
putchar(str[i]);
cout << endl;
}
int main()
{
int n;
__int64 temp = 1;
for(int i = 0; i < 20; i++)
xx[i] = temp, temp *= 3;
scanf("%d", &n);
while(n--)
{
int x;
len = 0;
scanf("%d", &x);
judge(x);
str[len++] = '0';
for(int i = 0; i < len; i++)
if (str[i] == '2')
{
str[i] = '0' - 1;
str[i + 1]++;
}
else if (str[i] == '3')
{
str[i] = '0';
str[i + 1]++;
}
bool flag = true;
for(int i = 0; i < len; i++)
if (str[i] == '0' - 1)
{
if (flag)
printf("%I64d", xx[i]), flag = false;
else
printf(",%I64d", xx[i]);
}
if (flag)
cout << "empty";
flag = true;
putchar(' ');
for(int i = 0; i < len; i++)
if (str[i] == '1')
{
if (flag)
printf("%I64d", xx[i]), flag = false;
else
printf(",%I64d", xx[i]);
}
putchar('\n');
}
return 0;
}