进制天平

Description
Give you a scale, a goods weigts m kilograms. And then give you some stones weighting 1, 3, 9, 27, …, 3^k. Of course, the number of different weights’ is only ONE.

Now put the goods on the left of scale. And then you should put some stones on two sides of scale to make the scale balanced.

Input
An integer m, stands for the weights of the goods (0 ≤ m ≤ 100 000 000)

Output
You should output two lines.

In the first line, the first integer N1 is the number of stones putting on the left of scale, and then N1 integers follow(in the ascend order), indicating the weight of stones putting on the left, seperated by one space. In the second line, please use the same way as the first line’s to output the N2, which is the number of stones putting on the right side. Then following N2 integers, which are in ascending order, indicate the stones’ weight putting on the right side.

Sample Input
42
30

Sample Output
3 3 9 27
1 81
0
2 3 27

#include 
#include 
#include 
using namespace std;
int n;
long long num[10009],three[30],add[10009],up;
void init()//3的N次方
{
    three[0]=1;
    for(int i=1; i<=30; i++)
        three[i]=3*three[i-1];
}
void to3(int a)//将十进制变为三进制
{
     up=0;
    while(a)
    {
        num[up++]=a%3;//反向储存
        a/=3;
    }
}
void fadd(int pos)//模拟三进制加一
{
    num[pos]++;
    for(int i=pos; i//由于反向储,所以正向相加
    {
        if(num[i]>=3)
        {
            num[i]=0;
            num[i+1]++;
            if(i==up-1)//提高最高位
                up++;
        }
    }
}
int main()
{
    init();
    while(~scanf("%d",&n))
    {
        memset(num,0,sizeof num);
        memset(add,0,sizeof add);
        to3(n);
        int left=0,right=0;
        for(int i=0; iif(num[i]==2)//由于每种砝码都只有一个
            {
                fadd(i);
                add[i]=1;
                left++;
            }
        }
        if(left!=0)
        {
            printf("%d",left);
            for(int i=0; iif(add[i])
                    printf(" %I64d",three[i]);
        }
        else
            printf("0");
        printf("\n");
        for(int i=0; iif(num[i])
                right++;
        printf("%d",right);
        for(int i=0; iif(num[i])
                printf(" %I64d",three[i]);
                puts("");
    }
    return 0;
}

Reflect:
1,由于每个砝码都是三的n次方,所以可以模拟三进制加法,但由于每种砝码都只有一个,所以三进制的位数字不可能超过1;
2,后来又想了一下,这里是不可能在左边和右边重复使用砝码的,因为左边加上的砝码会导致右边加上一个比它更重的砝码,这就使得左右加的砝码的重量不可能一样;

你可能感兴趣的:(进制天平)