No Tipping
InterviewTime limit1sMemory limit128 MB
Count the orders in which n packages can be removed from a lever on two fulcrums so the board never tips.
- Level
Medium6 of 10
- Topics
- Backtracking, Bit manipulation, Dynamic programming
- Solved
- No attempts yet
Problem
If you place an object on a lever arm, it exerts a twisting force around the lever's fulcrum. This twist is called torque, and its magnitude equals the object's weight multiplied by its distance from the fulcrum. If the object is to the left of the fulcrum the torque is counterclockwise; if it is to the right the torque is clockwise. The total torque around a support is the sum of the torques of every object on the lever (the board itself also counts as an object whose weight acts at its center).
There is a straight board of uniform thickness and evenly distributed weight. Its middle is the center of mass, which we call position 0, so the two ends of a board of length are at positions and . The board rests on two identical fulcrums at positions and . Several packages sit on the board; each package is given by an integer position (measured from the center, negative meaning to the left) and an integer weight.
You remove the packages one at a time. The board must never tip: it tips if the net torque around the left fulcrum (from the packages and the board's own weight) is counterclockwise, or if the net torque around the right fulcrum is clockwise. If the net torque at a fulcrum is exactly balanced (zero), the board does not tip. The board must stay balanced in the initial configuration and after every single removal (a board with no packages is always balanced).
For example, a board weighing 3kg and 20m long rests on the two fulcrums with six packages at positions having weights kg respectively.

For this configuration there are several removal orders that keep the board from tipping.
Input
The input consists of several test cases. Each test case begins with three integers: the length of the board (in meters, at least 3), the weight of the board (in kilograms), and the number of packages (). The board is always supported at positions and by two identical fulcrums. The following lines each contain two integers: the position of a package (measured from the center, negative meaning to the left) and its weight (in kilograms). The input ends with a line containing three zeros, which is not a test case.
Output
For each test case, output one line of the form Case X: C, where X is the test-case number starting from 1 and C is the number of distinct orders in which the packages can be removed one at a time so that the board never tips after any removal. Packages listed on different input lines are distinct even when they share the same position and weight. If the packages cannot all be removed without the board tipping — in particular, if the initial configuration already tips — output C as 0.