Nanosoft (Codeforces 1301E)
Tags: Implement, binary search

Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building.The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue.An Example of some correct logos:An Example of some incorrect logos:Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of $$$n$$$ rows and $$$m$$$ columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B').Adhami gave Warawreh $$$q$$$ options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is $$$0$$$.Warawreh couldn't find the best option himself so he asked you for help, can you help him?

Input: The first line of input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ $$$(1 \leq n , m \leq 500, 1 \leq q \leq 3 \cdot 10^{5})$$$  — the number of row, the number columns and the number of options.For the next $$$n$$$ lines, every line will contain $$$m$$$ characters. In the $$$i$$$-th line the $$$j$$$-th character will contain the color of the cell at the $$$i$$$-th row and $$$j$$$-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}.For the next $$$q$$$ lines, the input will contain four integers $$$r_1$$$, $$$c_1$$$, $$$r_2$$$ and $$$c_2$$$ $$$(1 \leq r_1 \leq r_2 \leq n, 1 \leq c_1 \leq c_2 \leq m)$$$. In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell $$$(r_1, c_1)$$$ and with the bottom-right corner in the cell $$$(r_2, c_2)$$$.

Output: For every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print $$$0$$$.

Note: Picture for the first test:The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray.

Sample Inputs:
5 5 5
RRGGB
RRGGY
YYBBG
YYBBR
RBBRG
1 1 5 5
2 2 5 5
2 2 3 3
1 1 3 5
4 4 5 5

6 10 5
RRRGGGRRGG
RRRGGGRRGG
RRRGGGYYBB
YYYBBBYYBB
YYYBBBRGRG
YYYBBBYBYB
1 1 6 10
1 3 3 10
2 2 6 6
1 7 6 10
2 1 5 10

8 8 8
RRRRGGGG
RRRRGGGG
RRRRGGGG
RRRRGGGG
YYYYBBBB
YYYYBBBB
YYYYBBBB
YYYYBBBB
1 1 8 8
5 2 5 7
3 1 8 6
2 3 5 8
1 2 6 8
2 1 5 5
2 1 7 7
6 5 7 5

Sample Outputs:
16
4
4
4
0

36
4
16
16
16

64
0
16
4
16
4
36
0

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

def g(u, v):
    return u * m1 + v

def sparse_table(x):
    ma = [0] * (n1 * m1)
    for i in range(n):
        for j in range(m):
            ma[g(i, j)] = x[f(i, j)]
        for j in range(len(s2) - 2):
            p = pow2[j]
            (k, l) = (s2[j], s2[j + 1])
            for _ in range(s2[j + 2] - s2[j + 1]):
                ma[g(i, l)] = max(ma[g(i, k)], ma[g(i, k + p)])
                (k, l) = (k + 1, l + 1)
    for j in range(m1):
        for i in range(len(s1) - 2):
            p = pow2[i]
            (k, l) = (s1[i], s1[i + 1])
            for _ in range(s1[i + 2] - s1[i + 1]):
                ma[g(l, j)] = max(ma[g(k, j)], ma[g(k + p, j)])
                (k, l) = (k + 1, l + 1)
    return ma

def get_max(l1, r1, l2, r2):
    d1 = (r1 - l1 + 1).bit_length() - 1
    d2 = (r2 - l2 + 1).bit_length() - 1
    (u1, v1) = (s1[d1] + l1, s1[d1] + r1 - pow2[d1] + 1)
    (u2, v2) = (s2[d2] + l2, s2[d2] + r2 - pow2[d2] + 1)
    ans = max(ma[g(u1, u2)], ma[g(u1, v2)], ma[g(v1, u2)], ma[g(v1, v2)])
    return ans

def binary_search(c1, c2):
    c = (c1 + c2 + 1) // 2
    while abs(c1 - c2) > 1:
        c = (c1 + c2 + 1) // 2
        if ok(c):
            c1 = c
        else:
            c2 = c
    c += 1
    while not ok(c):
        c -= 1
    return c

def ok(c):
    if c <= 0:
        return True
    (l3, r3, l4, r4) = (l1 + c - 1, r1 - c, l2 + c - 1, r2 - c)
    if not l3 <= r3 or not l4 <= r4:
        return False
    return True if get_max(l3, r3, l4, r4) >= c else False
(n, m, q) = map(int, input().split())
d = {'R': 1, 'G': 2, 'Y': 3, 'B': 4}
s = [0] * (n * m)
for i in range(n):
    s0 = list(input().rstrip().decode())
    for j in range(m):
        s[f(i, j)] = d[s0[j]]
(n0, n1, l) = (n, n, 1)
s1 = [0]
while l << 1 <= n:
    s1.append(n1)
    n0 -= l
    n1 += n0
    l <<= 1
s1.append(n1)
(m0, m1, l) = (m, m, 1)
s2 = [0]
while l << 1 <= m:
    s2.append(m1)
    m0 -= l
    m1 += m0
    l <<= 1
s2.append(m1)
pow2 = [1]
for _ in range(20):
    pow2.append(2 * pow2[-1])
x = [0] * (n * m)
for i in range(n - 1):
    for j in range(m - 1):
        if not s[f(i, j)] < s[f(i, j + 1)] < s[f(i + 1, j)] < s[f(i + 1, j + 1)]:
            continue
        x[f(i, j)] = 1
        d = 1
        while 0 <= min(i - d, j - d) and i + d + 1 < n and (j + d + 1 < m):
            (i1, j1) = (i - d, j - d)
            (i4, j4) = (i + d + 1, j + d + 1)
            ok0 = 1
            for k in range(d + 1):
                if not s[f(i1 + k, j1)] < s[f(i1 + k, j4)] < s[f(i4 - k, j1)] < s[f(i4 - k, j4)]:
                    ok0 = 0
                    break
            if ok0:
                for k in range(d + 1):
                    if not s[f(i1, j1 + k)] < s[f(i1, j4 - k)] < s[f(i4, j1 + k)] < s[f(i4, j4 - k)]:
                        ok0 = 0
                        break
            if not ok0:
                break
            x[f(i, j)] += 1
            d += 1
ma = sparse_table(x)
ans = []
inf = min(n, m) // 2 + 5
for _ in range(q):
    (r1, c1, r2, c2) = map(int, input().split())
    (l1, r1, l2, r2) = (r1 - 1, r2 - 1, c1 - 1, c2 - 1)
    c = binary_search(0, inf)
    ans0 = 4 * c * c
    ans.append(ans0)
sys.stdout.write('\n'.join(map(str, ans)))

Solution (Python):
import io, os
import sys
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
(n, m, q) = map(int, input().split())
C = [input().strip() for i in range(n)]
ATABLE = [[0] * m for i in range(n)]
for i in range(n - 1):
    for j in range(m - 1):
        if C[i][j] == 82 and C[i + 1][j] == 89 and (C[i][j + 1] == 71) and (C[i + 1][j + 1] == 66):
            for l in range(1, 5000):
                if 0 <= i - l and 0 <= j - l and (i + l + 1 < n) and (j + l + 1 < m):
                    True
                else:
                    break
                flag = 1
                for k in range(i - l, i + 1):
                    if C[k][j - l] != 82:
                        flag = 0
                        break
                    if C[k][j + l + 1] != 71:
                        flag = 0
                        break
                if flag == 0:
                    break
                for k in range(j - l, j + 1):
                    if C[i - l][k] != 82:
                        flag = 0
                        break
                    if C[i + l + 1][k] != 89:
                        flag = 0
                        break
                if flag == 0:
                    break
                for k in range(i + 1, i + l + 2):
                    if C[k][j - l] != 89:
                        flag = 0
                        break
                    if C[k][j + l + 1] != 66:
                        flag = 0
                        break
                if flag == 0:
                    break
                for k in range(j + 1, j + l + 2):
                    if C[i - l][k] != 71:
                        flag = 0
                        break
                    if C[i + l + 1][k] != 66:
                        flag = 0
                        break
                if flag == 0:
                    break
            ATABLE[i][j] = l
Sparse_table1 = [[ATABLE[i]] for i in range(n)]
for r in range(n):
    for i in range(m.bit_length() - 1):
        j = 1 << i
        B = []
        for k in range(len(Sparse_table1[r][-1]) - j):
            B.append(max(Sparse_table1[r][-1][k], Sparse_table1[r][-1][k + j]))
        Sparse_table1[r].append(B)
Sparse_table2 = [[[[Sparse_table1[i][j][k] for i in range(n)]] for k in range(len(Sparse_table1[0][j]))] for j in range(m.bit_length())]
for d in range(m.bit_length()):
    for c in range(len(Sparse_table1[0][d])):
        for i in range(n.bit_length() - 1):
            j = 1 << i
            B = []
            for k in range(len(Sparse_table2[d][c][-1]) - j):
                B.append(max(Sparse_table2[d][c][-1][k], Sparse_table2[d][c][-1][k + j]))
            Sparse_table2[d][c].append(B)
for query in range(q):
    (r1, c1, r2, c2) = map(int, input().split())
    r1 -= 1
    c1 -= 1
    r2 -= 1
    c2 -= 1
    if r1 == r2 or c1 == c2:
        print(0)
        continue
    OK = 0
    rd = (r2 - r1).bit_length() - 1
    cd = (c2 - c1).bit_length() - 1
    NG = 1 + max(Sparse_table2[cd][c1][rd][r1], Sparse_table2[cd][c1][rd][r2 - (1 << rd)], Sparse_table2[cd][c2 - (1 << cd)][rd][r1], Sparse_table2[cd][c2 - (1 << cd)][rd][r2 - (1 << rd)])
    while NG - OK > 1:
        mid = (NG + OK) // 2
        rr1 = r1 + mid - 1
        cc1 = c1 + mid - 1
        rr2 = r2 - mid + 1
        cc2 = c2 - mid + 1
        if rr1 >= rr2 or cc1 >= cc2:
            NG = mid
            continue
        rd = (rr2 - rr1).bit_length() - 1
        cd = (cc2 - cc1).bit_length() - 1
        if mid <= max(Sparse_table2[cd][cc1][rd][rr1], Sparse_table2[cd][cc1][rd][rr2 - (1 << rd)], Sparse_table2[cd][cc2 - (1 << cd)][rd][rr1], Sparse_table2[cd][cc2 - (1 << cd)][rd][rr2 - (1 << rd)]):
            OK = mid
        else:
            NG = mid
    sys.stdout.write(str((OK * 2) ** 2) + '\n')

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

    def STfunc(a, b):
        if a > b:
            return a
        else:
            return b

    class SparseTable:

        def __init__(self, grid):
            self.N = len(grid)
            self.M = len(grid[0])
            self.KN = self.N.bit_length() - 1
            self.KM = self.M.bit_length() - 1
            self.flatten = lambda n, m, kn, km: (n * self.M + m) * ((self.KN + 1) * (self.KM + 1)) + (kn * (self.KM + 1) + km)
            self.table = [0] * (self.flatten(self.N - 1, self.M - 1, self.KN, self.KM) + 1)
            for (i, line) in enumerate(grid):
                for (j, val) in enumerate(line):
                    self.table[self.flatten(i, j, 0, 0)] = val
            for km in range(1, self.KM + 1):
                for i in range(self.N):
                    for j in range(self.M):
                        j2 = j + (1 << km - 1)
                        if j2 <= self.M - 1:
                            self.table[self.flatten(i, j, 0, km)] = STfunc(self.table[self.flatten(i, j, 0, km - 1)], self.table[self.flatten(i, j2, 0, km - 1)])
            for kn in range(1, self.KN + 1):
                for km in range(self.KM + 1):
                    for i in range(self.N):
                        i2 = i + (1 << kn - 1)
                        for j in range(self.M):
                            if i2 <= self.N - 1:
                                self.table[self.flatten(i, j, kn, km)] = STfunc(self.table[self.flatten(i, j, kn - 1, km)], self.table[self.flatten(i2, j, kn - 1, km)])

        def query(self, r1, c1, r2, c2):
            kr = (r2 - r1).bit_length() - 1
            kc = (c2 - c1).bit_length() - 1
            r2 -= 1 << kr
            c2 -= 1 << kc
            return STfunc(STfunc(self.table[self.flatten(r1, c1, kr, kc)], self.table[self.flatten(r2, c1, kr, kc)]), STfunc(self.table[self.flatten(r1, c2, kr, kc)], self.table[self.flatten(r2, c2, kr, kc)]))
    (H, W, Q) = map(int, input().split())
    grid = []
    for _ in range(H):
        grid.append(input())
    R = [[0] * W for _ in range(H)]
    G = [[0] * W for _ in range(H)]
    Y = [[0] * W for _ in range(H)]
    B = [[0] * W for _ in range(H)]
    R_enc = ord('R')
    G_enc = ord('G')
    Y_enc = ord('Y')
    B_enc = ord('B')
    for h in range(H):
        for w in range(W):
            if grid[h][w] == R_enc:
                R[h][w] = 1
            elif grid[h][w] == G_enc:
                G[h][w] = 1
            elif grid[h][w] == Y_enc:
                Y[h][w] = 1
            else:
                B[h][w] = 1
    for h in range(1, H):
        for w in range(1, W):
            if R[h][w]:
                tmp = min(R[h - 1][w - 1], R[h - 1][w], R[h][w - 1]) + 1
                if tmp > 1:
                    R[h][w] = tmp
    for h in range(1, H):
        for w in range(W - 2, -1, -1):
            if G[h][w]:
                tmp = min(G[h - 1][w + 1], G[h - 1][w], G[h][w + 1]) + 1
                if tmp > 1:
                    G[h][w] = tmp
    for h in range(H - 2, -1, -1):
        for w in range(1, W):
            if Y[h][w]:
                tmp = min(Y[h + 1][w - 1], Y[h + 1][w], Y[h][w - 1]) + 1
                if tmp > 1:
                    Y[h][w] = tmp
    for h in range(H - 2, -1, -1):
        for w in range(W - 2, -1, -1):
            if B[h][w]:
                tmp = min(B[h + 1][w + 1], B[h + 1][w], B[h][w + 1]) + 1
                if tmp > 1:
                    B[h][w] = tmp
    M = [[0] * W for _ in range(H)]
    for h in range(H):
        for w in range(W):
            if h < H - 1 and w < W - 1:
                M[h][w] = min(R[h][w], G[h][w + 1], Y[h + 1][w], B[h + 1][w + 1])
    ST = SparseTable(M)
    ans = [None] * Q
    for q in range(Q):
        (r1, c1, r2, c2) = map(int, input().split())
        r1 -= 1
        c1 -= 1
        r2 -= 1
        c2 -= 1
        ok = 0
        ng = 501
        mid = 250
        while ng - ok > 1:
            R1 = r1 + mid - 1
            C1 = c1 + mid - 1
            R2 = r2 - mid + 1
            C2 = c2 - mid + 1
            if R1 >= R2 or C1 >= C2:
                ng = mid
                mid = (ok + ng) // 2
                continue
            if ST.query(R1, C1, R2, C2) >= mid:
                ok = mid
            else:
                ng = mid
            mid = (ok + ng) // 2
        ans[q] = (2 * ok) ** 2
    sys.stdout.write('\n'.join(map(str, ans)))
if __name__ == '__main__':
    main()