Great Grids (Codeforces 1844E)
Tags: Others, 2-sat

An $$$n \times m$$$ grid of characters is called great if it satisfies these three conditions:   Each character is either 'A', 'B', or 'C'.  Every $$$2 \times 2$$$ contiguous subgrid contains all three different letters.  Any two cells that share a common edge contain different letters. Let $$$(x,y)$$$ denote the cell in the $$$x$$$-th row from the top and $$$y$$$-th column from the left.You want to construct a great grid that satisfies $$$k$$$ constraints. Each constraint consists of two cells, $$$(x_{i,1},y_{i,1})$$$ and $$$(x_{i,2},y_{i,2})$$$, that share exactly one corner. You want your great grid to have the same letter in cells $$$(x_{i,1},y_{i,1})$$$ and $$$(x_{i,2},y_{i,2})$$$.Determine whether there exists a great grid satisfying all the constraints. 

Input: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The description of the test cases follows.The first line of each test case contains three integers, $$$n$$$, $$$m$$$, and $$$k$$$ ($$$2 \le n,m \le 2 \cdot 10^3$$$, $$$1 \le k \le 4 \cdot 10^3$$$).Each of the next $$$k$$$ lines contains four integers, $$$x_{i,1}$$$, $$$y_{i,1}$$$, $$$x_{i,2}$$$, and $$$y_{i,2}$$$ ($$$1 \le x_{i,1} < x_{i,2} \le n$$$, $$$1 \le y_{i,1},y_{i,2} \le m$$$). It is guaranteed that either $$$(x_{i,2},y_{i,2}) = (x_{i,1}+1,y_{i,1}+1)$$$ or $$$(x_{i,2},y_{i,2}) = (x_{i,1}+1,y_{i,1}-1)$$$.The pairs of cells are pairwise distinct, i.e. for all $$$1 \le i < j \le k$$$, it is not true that $$$x_{i,1} = x_{j,1}$$$, $$$y_{i,1} = y_{j,1}$$$, $$$x_{i,2} = x_{j,2}$$$, and $$$y_{i,2} = y_{j,2}$$$.It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^3$$$.It is guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^3$$$.It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$4 \cdot 10^3$$$.

Output: For each test case, output "YES" if a great grid satisfying all the constraints exists and "NO" otherwise.You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.

Note: In the first test case, the following great grid satisfies all the constraints: BABCCBCAACABIn the second test case, the two constraints imply that cells $$$(1,1)$$$ and $$$(2,2)$$$ have the same letter and cells $$$(1,2)$$$ and $$$(2,1)$$$ have the same letter, which makes it impossible for the only $$$2 \times 2$$$ subgrid to contain all three different letters.

Sample Inputs:
4
3 4 4
1 1 2 2
2 1 3 2
1 4 2 3
2 3 3 2
2 7 2
1 1 2 2
1 2 2 1
8 5 4
1 2 2 1
1 5 2 4
7 1 8 2
7 4 8 5
8 5 4
1 2 2 1
1 5 2 4
7 1 8 2
7 5 8 4

Sample Outputs:
YES
NO
YES
NO

Solution (Python):
class graph_coloring:

    def __init__(self, pairs):
        self.colored = {}
        self.adjacency = {}
        self.pairs = pairs
        for (x, y) in pairs:
            if x not in self.adjacency:
                self.adjacency[x] = set()
            self.adjacency[x].add(y)
            if y not in self.adjacency:
                self.adjacency[y] = set()
            self.adjacency[y].add(x)

    def dfs_recursive(self, node, color):
        if node not in self.colored:
            self.colored[node] = color
            return all((self.dfs(neighbor, color * self.pairs[node, neighbor]) if (node, neighbor) in self.pairs else self.dfs(neighbor, color * self.pairs[neighbor, node]) for neighbor in self.adjacency[node]))
        else:
            return self.colored[node] == color

    def dfs_iterative(self, first_node, first_color):
        stack = [(first_node, first_color)]
        while len(stack) > 0:
            (node, color) = stack.pop()
            if node not in self.colored:
                self.colored[node] = color
                for neighbor in self.adjacency[node]:
                    if node < neighbor:
                        stack.append((neighbor, color * self.pairs[node, neighbor]))
                    else:
                        stack.append((neighbor, color * self.pairs[neighbor, node]))
            elif self.colored[node] != color:
                return False
        return True

    def run(self):
        for node in self.adjacency:
            if node not in self.colored:
                if not self.dfs_iterative(node, 1):
                    return 'No'
        return 'Yes'

def q5_finalized(row, column, constraints):
    constraints_dict = {}
    for [x1, y1, x2, y2] in constraints:
        if y2 == y1 + 1:
            if (x1 - 1, row + y1 - 1) in constraints_dict and constraints_dict[x1 - 1, row + y1 - 1] == 1:
                return 'No'
            constraints_dict[x1 - 1, row + y1 - 1] = -1
        elif y2 == y1 - 1:
            if (x1 - 1, row + y2 - 1) in constraints_dict and constraints_dict[x1 - 1, row + y2 - 1] == -1:
                return 'No'
            constraints_dict[x1 - 1, row + y2 - 1] = 1
    g = graph_coloring(constraints_dict)
    return g.run()
num_tests = int(input())
for i in range(num_tests):
    [row, col, num_constraints] = list(map(int, input().split()))
    constraints = []
    for j in range(num_constraints):
        constraints.append(list(map(int, input().split())))
    print(q5_finalized(row, col, constraints))

Solution (Python):
class graph_coloring:

    def __init__(self, pairs):
        self.colored = {}
        self.adjacency = {}
        self.pairs = pairs
        for (x, y) in pairs:
            if x not in self.adjacency:
                self.adjacency[x] = set()
            self.adjacency[x].add(y)
            if y not in self.adjacency:
                self.adjacency[y] = set()
            self.adjacency[y].add(x)

    def dfs_recursive(self, node, color):
        if node not in self.colored:
            self.colored[node] = color
            return all((self.dfs(neighbor, color * self.pairs[node, neighbor]) if (node, neighbor) in self.pairs else self.dfs(neighbor, color * self.pairs[neighbor, node]) for neighbor in self.adjacency[node]))
        else:
            return self.colored[node] == color

    def dfs_iterative(self, first_node, first_color):
        stack = [(first_node, first_color)]
        while len(stack) > 0:
            (node, color) = stack.pop()
            if node not in self.colored:
                self.colored[node] = color
                for neighbor in self.adjacency[node]:
                    if node < neighbor:
                        stack.append((neighbor, color * self.pairs[node, neighbor]))
                    else:
                        stack.append((neighbor, color * self.pairs[neighbor, node]))
            elif self.colored[node] != color:
                return False
        return True

    def run(self):
        for node in self.adjacency:
            if node not in self.colored:
                if not self.dfs_iterative(node, 1):
                    return 'No'
        return 'Yes'

def q5_finalized(row, column, constraints):
    constraints_dict = {}
    for [x1, y1, x2, y2] in constraints:
        if y2 == y1 + 1:
            if (x1 - 1, row + y1 - 1) in constraints_dict and constraints_dict[x1 - 1, row + y1 - 1] == 1:
                return 'No'
            constraints_dict[x1 - 1, row + y1 - 1] = -1
        elif y2 == y1 - 1:
            if (x1 - 1, row + y2 - 1) in constraints_dict and constraints_dict[x1 - 1, row + y2 - 1] == -1:
                return 'No'
            constraints_dict[x1 - 1, row + y2 - 1] = 1
    g = graph_coloring(constraints_dict)
    return g.run()
num_tests = int(input())
for i in range(num_tests):
    [row, col, num_constraints] = list(map(int, input().split()))
    constraints = []
    for j in range(num_constraints):
        constraints.append(list(map(int, input().split())))
    print(q5_finalized(row, col, constraints))

Solution (Python):
import sys
input = sys.stdin.readline

def readList():
    return list(map(int, input().split()))

def readInt():
    return int(input())

def readInts():
    return map(int, input().split())

def readStr():
    return input().strip()

def solve():
    (n, m, k) = readInts()
    graph = [[] for _ in range(n + m)]
    for _ in range(k):
        (a, b, u, v) = readInts()
        if v == b + 1:
            graph[a - 1].append([n + b - 1, 0])
            graph[n + b - 1].append([a - 1, 0])
        else:
            graph[a - 1].append([n + b - 2, 1])
            graph[n + b - 2].append([a - 1, 1])
    v = [-1] * (n + m)
    for i in range(n + m):
        if v[i] != -1:
            continue
        v[i] = 0
        st = [i]
        while st:
            node = st.pop()
            for (nei, w) in graph[node]:
                if v[nei] == -1:
                    st.append(nei)
                    v[nei] = v[node] ^ w
                elif v[nei] != v[node] ^ w:
                    return 'NO'
    return 'YES'
for _ in range(int(input())):
    print(solve())