Under construction

Still being built. Things may change

Count the Cows

Time limit1sMemory limit512 MB

Summary
For each query, count the cows on the diagonal from (x, y) to (x+d, y+d) in a base-3 fractal pattern where coordinates reach 10^18.
Level

Medium7 of 10

Topics
Dynamic programming, Math, Recursion
Solved
No attempts yet

Problem

Farmer John's cows have spread out along his largest pasture, which can be regarded as a large 2D grid of square cells (picture a huge chessboard).

The pattern of cows across the pasture is quite fascinating. For every cell (x,y)(x,y) with x≥0x\ge 0 and y≥0y\ge 0, there is a cow at (x,y)(x,y) if, for all integers k≥0k\ge 0, the remainders of ⌊x3k⌋\left\lfloor \frac{x}{3^k}\right\rfloor and ⌊y3k⌋\left\lfloor \frac{y}{3^k}\right\rfloor modulo three have the same parity. In other words, both remainders are odd (equal to 1), or both are even (equal to 0 or 2). The cells with 0≤x,y<90\le x,y<9 that contain cows are marked with ones in the diagram below.

        x
    012345678

  0 101000101
  1 010000010
  2 101000101
  3 000101000
y 4 000010000
  5 000101000
  6 101000101
  7 010000010
  8 101000101

FJ wants to know how many cows lie in a region of his pasture. He asks QQ queries, each with three integers xix_i, yiy_i, did_i. For each query, count the cows in the cells along the diagonal from (xi,yi)(x_i,y_i) to (xi+di,yi+di)(x_i+d_i,y_i+d_i), endpoints included.

Input

The first line contains QQ (1≤Q≤1041\le Q\le 10^4), the number of queries.

The next QQ lines each contain three integers did_i, xix_i, and yiy_i (0≤xi,yi,di≤10180\le x_i,y_i,d_i\le 10^{18}).

Output

Print QQ lines, one for each query.

Examples1

  1. Example 1

    Input
    8
    10 0 0
    10 0 1
    9 0 2
    8 0 2
    0 1 7
    1 1 7
    2 1 7
    1000000000000000000 1000000000000000000 1000000000000000000
    
    Expected output
    11
    0
    4
    3
    1
    2
    2
    1000000000000000001