Connection Status:
Competition Arena > Apothecary
SRM 204 · 2004-07-21 · by vorthys · Greedy, Math
Class Name: Apothecary
Return Type: int[]
Method Name: balance
Arg Types: (int)
Problem Statement

Problem Statement

An accurate scale is one of the most important tools of the apothecary (an old-time pharmacist). To measure the weight of an object, the apothecary places the object on one pan of the scale, along with some weights of known size, and adds more weights of known size to the other pan until the scales balance. For example, if an object weighs 17 grains, the apothecary could balance the scales by placing a 1-grain weight and a 9-grain weight in the pan with the object, and a 27-grain weight in the other pan.

The apothecary owns weights in a range of sizes starting at 1 grain. In particular, he owns one weight for each power of 3: 1 grain, 3 grains, 9 grains, 27 grains, etc. Determine, for an object weighing W grains, how to distribute the weights among the pans to balance the object. This distribution will be unique. Return a int[] of the weights used. The sign of each weight should be negative if the weight goes in the same pan as the object, and positive if it goes in the other pan. The int[] should be arranged in increasing order.

Constraints

  • W is between 1 and 1000000, inclusive.
Examples
0)
17
Returns: { -9,  -1,  27 }

The example above.

1)
1
Returns: { 1 }

A 1-grain weight is placed in the pan opposite the object being measured.

2)
2016
Returns: { -243,  -9,  81,  2187 }

A 9-grain weight and a 243-grain weight are placed in the pan with the object, and an 81-grain weight and a 2187-grain weight are placed in the opposite pan.

3)
1000000
Returns: { -531441,  -59049,  -6561,  -243,  -27,  1,  81,  729,  2187,  1594323 }
4)
2
Returns: { -1,  3 }

Submissions are judged against all 41 archived test cases, of which 5 are shown here. Case numbers match the judge’s.

Coding Area

Language: C++17 · define a public class Apothecary with a public method vector<int> balance(int W) · 41 test cases · 2 s / 256 MB per case

Submitting as anonymous