1702

Eva's Balance
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 4199   Accepted: 2021

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、27、81 .. 3^K... 3^19 砝碼,天平左邊給定一個重量值w (1=< w <= (3^20-1)/2 ),求如何擺放砝碼使天平兩端達到平衡。因此通過將其轉化爲三進制進行判斷該不該在左側加砝碼,以及在左右兩側加多少砝碼。同時,逗號的取捨以及空格的選取通過循環進行實現。

結果 內存 時間 語言 代碼長度
Accepted 204K 63MS C 954B
#include<stdio.h>
#include<math.h>//下面用到了pow()函數;
#include<string.h>
int i, j, k, m;
int flag1 , flag2 ;
int main()
{
	int N;
	scanf("%d", &N);
	while (N--)//組別非負;
	{
		int a[25];
		memset(a, 0, sizeof(a));//將數組內的值都初始化爲0;

		scanf("%d", &m);
		for (i = 0; m != 0; i++)//將其轉化爲三位制,當m爲0結束循環;
		{
			a[i] = m % 3;
			m = (m - a[i]) / 3;
		}
		for (j = 0; j<i; j++)//三進制內運算(數組內各元素只能爲-1,0,1);
		{
			if (a[j] == 2)
			{
				a[j + 1]++;
				a[j] = -1;
			}
			else if (a[j] == 3)
			{
				a[j + 1]++;
				a[j] = 0;
			}
		}
		flag1 = 0, flag2 = 0;
		for (k = 0; k <= i; k++)
		{
			if (a[k] == -1)
			{
				if (flag1)printf(",");
				flag1 = 1;
				printf("%.0lf", pow((double)3, (double)k));
			}

		}
		if (flag1 == 0)printf("empty");//如果左邊無需加法嗎,則輸出"empty";
		printf(" ");
		for (k = 0; k <= i; k++)
		{

			if (a[k] == 1)
			{
				if (flag2)printf(",");
				flag2 = 1;
				printf("%.0lf", pow((double)3, (double)k));
			}
		}
		printf("\n");
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章