This page is still under construction.

Parts of this page are still being built. What you see may change.

Buckets

Time limit2sMemory limit128 MB

Summary
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 aa and bb 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 xx liters and bucket B starts with yy 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 Oi=(si,ti)O_i = (s_i, t_i) is called a target amount. The target amount OiO_i is achievable from (s,t)(s, t) if some sequence of zero or more of the operations above turns buckets holding exactly ss and tt liters into buckets holding exactly sis_i and tit_i liters.

You are given target amounts O1,O2,…,OnO_1, O_2, \dots, O_n. Find the longest subsequence Oi1,Oi2,…,OilO_{i_1}, O_{i_2}, \dots, O_{i_l} with i1<i2<⋯<ili_1 < i_2 < \dots < i_l such that each one is achievable from the previous one. The subsequence does not have to be consecutive, so O1,O4,O6,O8O_1, O_4, O_6, O_8 is allowed when nn is large enough, and the previous one for Oi1O_{i_1} is the starting pair (x,y)(x, y). 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 ll of the longest such subsequence.

Input

The first line has the number of test cases TT. Each test case starts with a line of five integers aa, bb, xx, yy, and nn (1≤a,b≤1091 \le a, b \le 10^9, 0≤x≤a0 \le x \le a, 0≤y≤b0 \le y \le b, 1≤n≤2000001 \le n \le 200000), where aa and bb are the capacities of A and B, xx and yy are the starting amounts of water in A and B, and nn is the number of target amounts. Each of the next nn lines has a target amount as two integers ss and tt (0≤s≤a0 \le s \le a, 0≤t≤b0 \le t \le b), 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 (x,y)(x, y).

Examples1

  1. Example 1

    Input
    2
    3 4 1 2 4
    1 2
    0 3
    3 4
    3 3
    8 2 3 1 7
    1 0
    0 1
    0 0
    1 0
    0 1
    0 2
    6 0
    
    Expected output
    4
    6