New Year and Domino (Codeforces 611C)
Tags: Implement, dp

They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so.Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right.Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid.Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?

Input: The first line of the input contains two integers h and w (1 ≤ h, w ≤ 500) – the number of rows and the number of columns, respectively.The next h lines describe a grid. Each line contains a string of the length w. Each character is either '.' or '#' — denoting an empty or forbidden cell, respectively.The next line contains a single integer q (1 ≤ q ≤ 100 000) — the number of queries.Each of the next q lines contains four integers r1i, c1i, r2i, c2i (1 ≤ r1i ≤ r2i ≤ h, 1 ≤ c1i ≤ c2i ≤ w) — the i-th query. Numbers r1i and c1i denote the row and the column (respectively) of the upper left cell of the rectangle. Numbers r2i and c2i denote the row and the column (respectively) of the bottom right cell of the rectangle.

Output: Print q integers, i-th should be equal to the number of ways to put a single domino inside the i-th rectangle.

Note: A red frame below corresponds to the first query of the first sample. A domino can be placed in 4 possible ways.  

Sample Inputs:
5 8
....#..#
.#......
##.#....
##..#.##
........
4
1 1 2 3
4 1 4 1
1 2 4 5
2 5 5 8

7 39
.......................................
.###..###..#..###.....###..###..#..###.
...#..#.#..#..#.........#..#.#..#..#...
.###..#.#..#..###.....###..#.#..#..###.
.#....#.#..#....#.....#....#.#..#..#.#.
.###..###..#..###.....###..###..#..###.
.......................................
6
1 1 3 20
2 10 6 30
2 10 7 30
2 2 7 7
1 7 7 7
1 8 7 8

Sample Outputs:
4
0
10
15

53
89
120
23
0
2

Solution (Python):
def main():
    (h, w) = map(int, input().split())
    l = [[c == '.' for c in input()] for _ in range(h)]
    ver = [[0] * (w + 1) for _ in range(h + 1)]
    for (y, aa, bb, l0, l1) in zip(range(h - 1), ver, ver[1:], l, l[1:]):
        for x in range(w):
            bb[x + 1] = (l0[x] and l1[x]) + bb[x] + aa[x + 1] - aa[x]
    hor = [[0] * (w + 1) for _ in range(h + 1)]
    for (y, aa, bb, l0) in zip(range(h), hor, hor[1:], l):
        for x in range(w - 1):
            bb[x + 1] = (l0[x] and l0[x + 1]) + bb[x] + aa[x + 1] - aa[x]
    res = []
    for _ in range(int(input())):
        (r1, c1, r2, c2) = map(int, input().split())
        r1 -= 1
        c1 -= 1
        res.append(str(ver[r2 - 1][c2] - ver[r1][c2] - ver[r2 - 1][c1] + ver[r1][c1] + hor[r2][c2 - 1] - hor[r1][c2 - 1] - hor[r2][c1] + hor[r1][c1]))
    print('\n'.join(res))
if __name__ == '__main__':
    main()

Solution (Python):
def solveQuery(hor, ver, q):
    (r1, c1, r2, c2) = tuple(q)
    horVal = hor[r2][c2] - hor[r1 - 1][c2] - hor[r2][c1] + hor[r1 - 1][c1]
    verVal = ver[r2][c2] - ver[r2][c1 - 1] - ver[r1][c2] + ver[r1][c1 - 1]
    if r2 - r1 == 0:
        verVal = 0
    if c2 - c1 == 0:
        horVal = 0
    return horVal + verVal

def solve(r, c, s, qs):
    hor = [[0 for _ in range(c + 1)] for _ in range(r + 1)]
    ver = [[0 for _ in range(c + 1)] for _ in range(r + 1)]
    for i in range(1, r + 1):
        for j in range(2, c + 1):
            if s[i - 1][j - 1] == s[i - 1][j - 2] == '.':
                hor[i][j] = 1
    for i in range(1, r + 1):
        for j in range(3, c + 1):
            hor[i][j] += hor[i][j - 1]
    for i in range(2, r + 1):
        for j in range(2, c + 1):
            hor[i][j] += hor[i - 1][j]
    for i in range(2, r + 1):
        for j in range(1, c + 1):
            if s[i - 1][j - 1] == s[i - 2][j - 1] == '.':
                ver[i][j] = 1
    for i in range(3, r + 1):
        for j in range(1, c + 1):
            ver[i][j] += ver[i - 1][j]
    for i in range(2, r + 1):
        for j in range(2, c + 1):
            ver[i][j] += ver[i][j - 1]
    for q in qs:
        print(solveQuery(hor, ver, q))
(r, c) = (int(n) for n in input().split())
s = []
for i in range(1, r + 1):
    s.append(input())
lq = int(input())
qs = []
for i in range(lq):
    qs.append([int(n) for n in input().split()])
solve(r, c, s, qs)

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

def ceil(x):
    if x != int(x):
        x = int(x) + 1
    return x

def factorial(x, m):
    val = 1
    while x > 0:
        val = val * x % m
        x -= 1
    return val

def fact(x):
    val = 1
    while x > 0:
        val *= x
        x -= 1
    return val

def swaparr(arr, a, b):
    temp = arr[a]
    arr[a] = arr[b]
    arr[b] = temp

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

def lcm(a, b):
    return a * b // gcd(a, b)

def nCr(n, k):
    if k > n:
        return 0
    if k > n - k:
        k = n - k
    res = 1
    for i in range(k):
        res = res * (n - i)
        res = res / (i + 1)
    return int(res)

def upper_bound(a, x, lo=0, hi=None):
    if hi == None:
        hi = len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo

def primefs(n):
    primes = {}
    while n % 2 == 0 and n > 0:
        primes[2] = primes.get(2, 0) + 1
        n = n // 2
    for i in range(3, int(n ** 0.5) + 2, 2):
        while n % i == 0 and n > 0:
            primes[i] = primes.get(i, 0) + 1
            n = n // i
    if n > 2:
        primes[n] = primes.get(n, 0) + 1
    return primes

def power(x, y, p):
    res = 1
    x = x % p
    if x == 0:
        return 0
    while y > 0:
        if y & 1 == 1:
            res = res * x % p
        y = y >> 1
        x = x * x % p
    return res

def swap(a, b):
    temp = a
    a = b
    b = temp
    return (a, b)

def find(x, link):
    p = x
    while p != link[p]:
        p = link[p]
    while x != p:
        nex = link[x]
        link[x] = p
        x = nex
    return p

def union(x, y, link, size):
    x = find(x, link)
    y = find(y, link)
    if size[x] < size[y]:
        (x, y) = swap(x, y)
    if x != y:
        size[x] += size[y]
        link[y] = x

def sieve(n):
    prime = [True for i in range(n + 1)]
    (prime[0], prime[1]) = (False, False)
    p = 2
    while p * p <= n:
        if prime[p] == True:
            for i in range(p * p, n + 1, p):
                prime[i] = False
        p += 1
    return prime

def phi(n):
    result = n
    p = 2
    while p * p <= n:
        if n % p == 0:
            while n % p == 0:
                n = n // p
            result = result * (1.0 - 1.0 / float(p))
        p = p + 1
    if n > 1:
        result = result * (1.0 - 1.0 / float(n))
    return int(result)

def is_prime(n):
    if n == 0:
        return False
    if n == 1:
        return True
    for i in range(2, int(n ** (1 / 2)) + 1):
        if not n % i:
            return False
    return True
MAXN = int(100000.0 + 5)

def spf_sieve():
    spf[1] = 1
    for i in range(2, MAXN):
        spf[i] = i
    for i in range(4, MAXN, 2):
        spf[i] = 2
    for i in range(3, ceil(MAXN ** 0.5), 2):
        if spf[i] == i:
            for j in range(i * i, MAXN, i):
                if spf[j] == j:
                    spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
    res = []
    for i in range(2, int(x ** 0.5) + 1):
        while x % i == 0:
            res.append(i)
            x //= i
    if x != 1:
        res.append(x)
    return res

def factors(n):
    res = []
    for i in range(1, int(n ** 0.5) + 1):
        if n % i == 0:
            res.append(i)
            res.append(n // i)
    return list(set(res))

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

def float_array():
    return list(map(float, input().strip().split()))

def str_array():
    return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math
from bisect import bisect_left

def solve():
    (h, w) = map(int, input().split())
    piles = [list(input().rstrip()) for x in range(h)]
    dot = '.'
    hatch = '#'
    dp = [[0 for i in range(w + 1)] for j in range(h + 1)]
    vr = [[0 for i in range(w + 1)] for j in range(h + 1)]
    hr = [[0 for i in range(w + 1)] for j in range(h + 1)]
    for i in range(1, w):
        if piles[0][i] == dot and piles[0][i - 1] == dot:
            dp[1][i + 1] = dp[1][i] + 1
        else:
            dp[1][i + 1] = dp[1][i]
    for i in range(1, h):
        if piles[i][0] == dot and piles[i - 1][0] == dot:
            dp[i + 1][1] = dp[i][1] + 1
        else:
            dp[i + 1][1] = dp[i][1]
    for i in range(1, h):
        for j in range(1, w):
            if piles[i][j - 1] == dot and piles[i - 1][j] == dot and (piles[i][j] == dot):
                dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1] - dp[i][j] + 2
            elif piles[i][j] == hatch:
                dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1] - dp[i][j]
            elif piles[i][j - 1] == dot or piles[i - 1][j] == dot:
                dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1] - dp[i][j] + 1
            elif piles[i][j - 1] == hatch and piles[i - 1][j] == hatch:
                dp[i + 1][j + 1] = dp[i + 1][j] + dp[i][j + 1] - dp[i][j]
    for i in range(h):
        for j in range(w):
            if i > 0:
                if piles[i][j] == dot and piles[i - 1][j] == dot:
                    vr[i + 1][j + 1] = vr[i + 1][j] + 1
                else:
                    vr[i + 1][j + 1] = vr[i + 1][j]
            if j > 0:
                if piles[i][j] == dot and piles[i][j - 1] == dot:
                    hr[i + 1][j + 1] = hr[i][j + 1] + 1
                else:
                    hr[i + 1][j + 1] = hr[i][j + 1]
    q = int(input())
    for _ in range(q):
        (r1, c1, r2, c2) = map(int, input().split())
        val = vr[r1][c2] - vr[r1][c1 - 1] + hr[r2][c1] - hr[r1 - 1][c1]
        print(dp[r2][c2] - dp[r2][c1 - 1] - dp[r1 - 1][c2] + dp[r1 - 1][c1 - 1] - val)
if __name__ == '__main__':
    for _ in range(1):
        solve()