|
| 1 | +def coord_to_num(x, y, n): |
| 2 | + # print(f"coord_to_num({x}, {y}, {n})") |
| 3 | + if n == 0: |
| 4 | + assert x == y == 1 |
| 5 | + return 1 |
| 6 | + |
| 7 | + is_top = x <= (1 << (n - 1)) |
| 8 | + is_left = y <= (1 << (n - 1)) |
| 9 | + |
| 10 | + if is_top and is_left: |
| 11 | + return coord_to_num(x, y, n - 1) |
| 12 | + elif not is_top and not is_left: |
| 13 | + return coord_to_num(x - (1 << (n - 1)), y - (1 << (n - 1)), n - 1) + (1 << (2*n - 2)) |
| 14 | + elif not is_top and is_left: |
| 15 | + return coord_to_num(x - (1 << (n - 1)), y, n - 1) + 2 * (1 << (2*n - 2)) |
| 16 | + else: |
| 17 | + return coord_to_num(x, y - (1 << (n - 1)), n - 1) + 3 * (1 << (2*n - 2)) |
| 18 | + |
| 19 | +def num_to_coord(num, n) -> tuple[int, int]: |
| 20 | + if n == 0: |
| 21 | + assert num == 1 |
| 22 | + return (1, 1) |
| 23 | + |
| 24 | + if num <= (1<<(2*n - 2)): |
| 25 | + return num_to_coord(num, n - 1) |
| 26 | + elif num <= 2 * (1 << (2*n - 2)): |
| 27 | + x, y = num_to_coord(num - (1 << (2*n - 2)), n - 1) |
| 28 | + return (x + (1 << (n - 1)), y + (1 << (n - 1))) |
| 29 | + elif num <= 3 * (1 << (2*n - 2)): |
| 30 | + x, y = num_to_coord(num - 2 * (1 << (2*n - 2)), n - 1) |
| 31 | + return (x + (1 << (n - 1)), y) |
| 32 | + else: |
| 33 | + x, y = num_to_coord(num - 3 * (1 << (2*n - 2)), n - 1) |
| 34 | + return (x, y + (1 << (n - 1))) |
| 35 | + |
| 36 | +for _ in range(int(input())): |
| 37 | + n = int(input()) |
| 38 | + q = int(input()) |
| 39 | + |
| 40 | + for _ in range(q): |
| 41 | + op, *x = input().split() |
| 42 | + |
| 43 | + if op == "->": |
| 44 | + x, y = map(int, x) |
| 45 | + print(coord_to_num(x, y, n)) |
| 46 | + elif op == "<-": |
| 47 | + x = int(x[0]) |
| 48 | + print(num_to_coord(x, n)[0], num_to_coord(x, n)[1]) |
0 commit comments