Count the Cows
Time limit1sMemory limit512 MB
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 with and , there is a cow at if, for all integers , the remainders of and 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 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 queries, each with three integers , , . For each query, count the cows in the cells along the diagonal from to , endpoints included.
Input
The first line contains (), the number of queries.
The next lines each contain three integers , , and ().
Output
Print lines, one for each query.