Tick, Tock (Codeforces 1758E)
Tags: Others, dsu

Tannhaus, the clockmaker in the town of Winden, makes mysterious clocks that measure time in $$$h$$$ hours numbered from $$$0$$$ to $$$h-1$$$. One day, he decided to make a puzzle with these clocks. The puzzle consists of an $$$n \times m$$$ grid of clocks, and each clock always displays some hour exactly (that is, it doesn't lie between two hours). In one move, he can choose any row or column and shift all clocks in that row or column one hour forward$$$^\dagger$$$.The grid of clocks is called solvable if it is possible to make all the clocks display the same time.While building his puzzle, Tannhaus suddenly got worried that it might not be possible to make the grid solvable. Some cells of the grid have clocks already displaying a certain initial time, while the rest of the cells are empty.Given the partially completed grid of clocks, find the number of ways$$$^\ddagger$$$ to assign clocks in the empty cells so that the grid is solvable. The answer can be enormous, so compute it modulo $$$10^9 + 7$$$.$$$^\dagger$$$ If a clock currently displays hour $$$t$$$ and is shifted one hour forward, then the clock will instead display hour $$$(t+1) \bmod h$$$.$$$^\ddagger$$$ Two assignments are different if there exists some cell with a clock that displays a different time in both arrangements.

Input: The first line of input contains $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases.The first line of each test case consists of 3 integers $$$n$$$, $$$m$$$, and $$$h$$$ ($$$1 \leq n, m \leq 2 \cdot 10^5$$$; $$$1 \leq h \leq 10^9$$$) — the number of rows in the grid, the number of columns in the grid, and the number of the hours in the day respectively.The next $$$n$$$ lines each contain $$$m$$$ integers, describing the clock grid. The integer $$$x$$$ ($$$-1 \leq x < h$$$) in the $$$i$$$-th row and the $$$j$$$-th column represents the initial hour of the corresponding clock, or if $$$x = -1$$$, an empty cell.It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Output: For each test case, output the number of ways to assign clocks in the empty cells so that the grid is solvable. The answer can be huge, so output it modulo $$$10^9 + 7$$$.

Note: For the first sample, this is a possible configuration for the clocks: 103032This is solvable since we can:   Move the middle column forward one hour.  Move the third column forward one hour.  Move the third column forward one hour.  Move the second row forward one hour.  After that all the clocks show one hour.For the second test case, it can be shown that there are no possible solvable clock configurations. 

Sample Inputs:
5
2 3 4
1 0 -1
-1 -1 2
2 2 10
1 2
3 5
4 5 1024
1 -1 -1 -1 -1
-1 -1 -1 1000 -1
-1 -1 -1 -1 69
420 -1 -1 999 -1
3 3 3
-1 -1 1
2 -1 1
2 -1 2
3 3 3
1 -1 2
-1 0 -1
-1 1 0

Sample Outputs:
4
0
73741817
0
1

Solution (Python):
import io, os
from collections import deque
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def main(t):
    M = 10 ** 9 + 7
    (m, n, h) = map(int, input().split())
    visited = [-1] * (m + n)
    group = [i for i in range(m + n)]
    neigh = [[] for _ in range(m + n)]

    def unionfind(root):
        son = root
        while root != group[root]:
            root = group[root]
        while son != root:
            temp = group[son]
            group[son] = root
            son = group[temp]
        return root
    rest = m + n - 1
    for i in range(m):
        temp = list(map(int, input().split()))
        for j in range(n):
            if temp[j] >= 0:
                neigh[i].append((j + m, temp[j]))
                neigh[j + m].append((i, temp[j]))
                root1 = unionfind(i)
                root2 = unionfind(j + m)
                if root1 != root2:
                    rest -= 1
                    group[max(root1, root2)] = min(root1, root2)
    queue = deque()
    for index in range(m + n):
        if visited[index] >= 0:
            continue
        queue.append((index, 0))
        while queue:
            (index, d) = queue.popleft()
            for (nextindex, tot) in neigh[index]:
                nextd = tot - d
                if nextd < 0:
                    nextd += h
                if visited[nextindex] >= 0 and visited[nextindex] != nextd:
                    print(0)
                    return
                if visited[nextindex] < 0:
                    visited[nextindex] = nextd
                    queue.append((nextindex, nextd))
    ans = pow(h, rest, M)
    print(ans)
T = int(input())
t = 1
while t <= T:
    main(t)
    t += 1

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
ans = []
mod = pow(10, 9) + 7
for _ in range(t):
    (n, m, h) = map(int, input().split())
    x = []
    for i in range(n):
        x0 = list(map(int, input().split()))
        for j in x0:
            x.append(j)
    ok = 1
    c = 0
    h1 = [-1] * m
    h2 = [-1] * n
    visit = [0] * m
    (c1, c2) = (0, 0)
    for i in range(n):
        if h2[i] ^ -1:
            continue
        (q, k) = ([i], 0)
        f = 0
        im = i * m
        for j in range(m):
            if x[im + j] ^ -1:
                (h1[j], h2[i]) = (0, 0)
                f = 1
                break
        if not f:
            continue
        c += 1
        c1 += 1
        c2 += 1
        while len(q) ^ k:
            u = q[k]
            um = u * m
            for j in range(m):
                if h1[j] ^ -1 and x[um + j] ^ -1:
                    l = j
                    break
            a = l
            for j in range(l + 1, m + l):
                b = j % m
                if x[um + b] == -1:
                    continue
                d = (x[um + b] - x[um + a]) % h
                if h1[b] == -1:
                    h1[b] = (h1[a] + d) % h
                    c1 += 1
                elif (h1[b] - h1[a]) % h ^ d:
                    ok = 0
                a = b
            for j in range(m):
                umj = um + j
                if visit[j] or x[umj] == -1:
                    continue
                visit[j] = 1
                for v in range(n):
                    vmj = v * m + j
                    if x[vmj] == -1:
                        continue
                    d = (x[vmj] - x[umj]) % h
                    if h2[v] == -1:
                        h2[v] = (h2[u] + d) % h
                        q.append(v)
                        c2 += 1
                    elif (h2[v] - h2[u]) % h ^ d:
                        ok = 0
            k += 1
    ans0 = 0 if not ok else pow(h, n + m - (c1 + c2) + c - 1, mod)
    ans.append(ans0)
sys.stdout.write('\n'.join(map(str, ans)))

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def f(u, v):
    return u * m + v
t = int(input())
ans = []
mod = pow(10, 9) + 7
for _ in range(t):
    (n, m, h) = map(int, input().split())
    x = []
    y = []
    z = [[] for _ in range(m)]
    for i in range(n):
        x0 = list(map(int, input().split()))
        s = []
        for j in range(m):
            if x0[j] ^ -1:
                s.append(j)
                z[j].append(i)
            x.append(x0[j])
        y.append(s)
    ok = 1
    c = 0
    h1 = [-1] * m
    h2 = [-1] * n
    visit = [0] * m
    (c1, c2) = (0, 0)
    for i in range(n):
        if h2[i] ^ -1 or not y[i]:
            continue
        c += 1
        (q, k) = ([i], 0)
        h1[y[i][0]] = 0
        h2[i] = 0
        c1 += 1
        c2 += 1
        while len(q) ^ k:
            u = q[k]
            yu = y[u]
            lyu = len(yu)
            for j in range(lyu):
                if h1[yu[j]] ^ -1:
                    l = j
                    break
            for j in range(l, l + lyu - 1):
                (a, b) = (yu[j % lyu], yu[(j + 1) % lyu])
                d = (x[f(u, b)] - x[f(u, a)]) % h
                if h1[b] == -1:
                    h1[b] = (h1[a] + d) % h
                    c1 += 1
                elif (h1[b] - h1[a]) % h ^ d:
                    ok = 0
            for j in yu:
                if visit[j]:
                    continue
                visit[j] = 1
                for v in z[j]:
                    d = (x[f(v, j)] - x[f(u, j)]) % h
                    if h2[v] == -1:
                        h2[v] = (h2[u] + d) % h
                        q.append(v)
                        c2 += 1
                    elif (h2[v] - h2[u]) % h ^ d:
                        ok = 0
            k += 1
    ans0 = 0 if not ok else pow(h, n + m - (c1 + c2) + c - 1, mod)
    ans.append(ans0)
sys.stdout.write('\n'.join(map(str, ans)))