atcoder#ABC193E. [ABC193E] Oversleeping

[ABC193E] Oversleeping

Score : 500500 points

Problem Statement

A train goes back and forth between Town AA and Town BB. It departs Town AA at time 00 and then repeats the following:

  • goes to Town BB, taking XX seconds;
  • stops at Town BB for YY seconds;
  • goes to Town AA, taking XX seconds;
  • stops at Town AA for YY seconds.

More formally, these intervals of time are half-open, that is, for each n=0,1,2,n = 0, 1, 2, \dots:

  • at time tt such that (2X+2Y)nt<(2X+2Y)n+X(2X + 2Y)n \leq t < (2X + 2Y)n + X, the train is going to Town BB;
  • at time tt such that (2X+2Y)n+Xt<(2X+2Y)n+X+Y(2X + 2Y)n + X \leq t < (2X + 2Y)n + X + Y, the train is stopping at Town BB;
  • at time tt such that (2X+2Y)n+X+Yt<(2X+2Y)n+2X+Y(2X + 2Y)n + X + Y \leq t < (2X + 2Y)n + 2X + Y, the train is going to Town AA;
  • at time tt such that (2X+2Y)n+2X+Yt<(2X+2Y)(n+1)(2X + 2Y)n + 2X + Y \leq t < (2X + 2Y)(n + 1), the train is stopping at Town AA.

Takahashi is thinking of taking this train to depart Town AA at time 00 and getting off at Town BB. After the departure, he will repeat the following:

  • be asleep for PP seconds;
  • be awake for QQ seconds.

Again, these intervals of time are half-open, that is, for each n=0,1,2,n = 0, 1, 2, \dots:

  • at time tt such that (P+Q)nt<(P+Q)n+P(P + Q)n \leq t < (P + Q)n + P, Takahashi is asleep;
  • at time tt such that (P+Q)n+Pt<(P+Q)(n+1)(P + Q)n + P \leq t < (P + Q)(n + 1), Takahashi is awake.

He can get off the train at Town BB if it is stopping at Town BB and he is awake. Determine whether he can get off at Town BB. If he can, find the earliest possible time to do so. Under the constraints of this problem, it can be proved that the earliest time is an integer.

You are given TT cases. Solve each of them.

Constraints

  • All values in input are integers.
  • 1T101 \leq T \leq 10
  • 1X1091 \leq X \leq 10^9
  • 1Y5001 \leq Y \leq 500
  • 1P1091 \leq P \leq 10^9
  • 1Q5001 \leq Q \leq 500

Input

Input is given from Standard Input in the following format:

TT

case1\rm case_1

case2\rm case_2

\hspace{9pt}\vdots

caseT\rm case_T

Each case is in the following format:

XX YY PP QQ

Output

Print TT lines. The ii-th line should contain the answer to casei\rm case_i. If there exists a time such that Takahashi can get off the train at Town BB, the line should contain the earliest such time; otherwise, the line should contain infinity.

3
5 2 7 6
1 1 3 1
999999999 1 1000000000 1
20
infinity
1000000000999999999

Let [a,b)[a, b) denote the interval at<ba \leq t < b.

In the first case, the train stops at Town BB during [5,7),[19,21),[33,35),[5, 7), [19, 21), [33, 35), \dots, and Takahashi is awake during [7,13),[20,26),[33,39),[7, 13), [20, 26), [33, 39), \dots, so he can get off at time 2020 at the earliest.