This page is still under construction.

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

CATS

Time limit2sMemory limit512 MB

Summary
Given X, L and N, simulate the buggy two-stack counter program with global bit flips and output the number it prints.
Level

Medium7 of 10

Topics
Simulation, Stack, Bit manipulation, Math
Solved
No attempts yet

Problem

Counter and Two Stacks (CATS) is an esoteric language built around a counter COUNTER and two stacks S1 and S2. Both stacks start as an infinite sequence of zeros.

PUSH inserts a value, POP removes the top, and ADD pops two values, adds them, and pushes the sum. If PUSH tries to insert a negative value, nothing is pushed; instead every element in that stack, including the infinite tail, has its least significant bit flipped (X⊕1X \oplus 1).

Mr. Panda wanted the XX-th multiple of NN strictly greater than LL, but the buggy pseudocode below prints something else. You may assume LL is not a multiple of NN.

COUNTER = X
WHILE COUNTER > 0
     S2 PUSH T1
     S1 POP
     FLIP LAST BINARY BIT OF ALL NUMBERS IN S1
     IF T2 > L
          COUNTER = COUNTER - 1
          IF COUNTER == 0 PRINT T2
     ELSE
          S2 PUSH N
          S2 PUSH N
          S2 ADD
          S2 ADD
          S1 PUSH T2
          S1 PUSH T2
          S2 POP
          S2 POP

T1 and T2 are the tops of S1 and S2. Inside the ELSE branch, S1 PUSH T2 uses T2 after the ADD steps. For each query, output the integer the pseudocode prints.

Input

The first line contains QQ, the number of queries.

Each of the next QQ lines contains three positive integers XX, LL, and NN. The value LL is not a multiple of NN.

Output

For each query, print the integer produced by the pseudocode, one per line.

Hint

Model the infinite zero tail with one parity bit plus a finite prefix array. FLIP and negative PUSH xor 1 into the tail bit and every prefix cell. POP on an empty prefix leaves only the tail.

Examples3

  1. Example 1

    Input
    2
    4 5 2
    18 6 4
    
    Expected output
    8
    9
    
  2. Example 2

    Input
    1
    4 5 2
    
    Expected output
    8
    
  3. Example 3

    Input
    1
    18 6 4
    
    Expected output
    9