Buckets
Time limit2sMemory limit128 MB
Two buckets allow fill, empty and pour moves, and the goal is the longest chain of the given target pairs where each pair is reachable from the previous one.
- Level
Medium7 of 10
- Topics
- Number theory, Implementation
- Solved
- No attempts yet
Problem
Buckets A and B hold and liters of water when full. Neither bucket has measuring lines, so you cannot tell how much water is inside unless the bucket is empty or full. Bucket A starts with liters and bucket B starts with liters. Next to them is a reservoir that holds an unlimited amount of water.
Because the buckets have no measuring lines, keeping the exact contents of both buckets known leaves you only these six operations.
- Empty A or B into the reservoir.
- Fill A or B from the reservoir.
- Move water from A to B until A is empty.
- Move water from A to B until B is full.
- Move water from B to A until B is empty.
- Move water from B to A until A is full.
A pair of integers is called a target amount. The target amount is achievable from if some sequence of zero or more of the operations above turns buckets holding exactly and liters into buckets holding exactly and liters.
You are given target amounts . Find the longest subsequence with such that each one is achievable from the previous one. The subsequence does not have to be consecutive, so is allowed when is large enough, and the previous one for is the starting pair . In other words, you make the first target amount from the starting pair using only the operations above, then the second from the first, and so on. Print the length of the longest such subsequence.
Input
The first line has the number of test cases . Each test case starts with a line of five integers , , , , and (, , , ), where and are the capacities of A and B, and are the starting amounts of water in A and B, and is the number of target amounts. Each of the next lines has a target amount as two integers and (, ), the amount of water to be held in A and in B.
Output
Print exactly one line for each test case. The line holds the length of the longest subsequence defined above. Print 0 when no target amount is achievable from .