Desktop Rearrangement (Codeforces 1674F)
Tags: Greedy, data structures

Your friend Ivan asked you to help him rearrange his desktop. The desktop can be represented as a rectangle matrix of size $$$n \times m$$$ consisting of characters '.' (empty cell of the desktop) and '*' (an icon).The desktop is called good if all its icons are occupying some prefix of full columns and, possibly, the prefix of the next column (and there are no icons outside this figure). In other words, some amount of first columns will be filled with icons and, possibly, some amount of first cells of the next (after the last full column) column will be also filled with icons (and all the icons on the desktop belong to this figure). This is pretty much the same as the real life icons arrangement.In one move, you can take one icon and move it to any empty cell in the desktop.Ivan loves to add some icons to his desktop and remove them from it, so he is asking you to answer $$$q$$$ queries: what is the minimum number of moves required to make the desktop good after adding/removing one icon?Note that queries are permanent and change the state of the desktop.

Input: The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000; 1 \le q \le 2 \cdot 10^5$$$) — the number of rows in the desktop, the number of columns in the desktop and the number of queries, respectively.The next $$$n$$$ lines contain the description of the desktop. The $$$i$$$-th of them contains $$$m$$$ characters '.' and '*' — the description of the $$$i$$$-th row of the desktop.The next $$$q$$$ lines describe queries. The $$$i$$$-th of them contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n; 1 \le y_i \le m$$$) — the position of the cell which changes its state (if this cell contained the icon before, then this icon is removed, otherwise an icon appears in this cell).

Output: Print $$$q$$$ integers. The $$$i$$$-th of them should be the minimum number of moves required to make the desktop good after applying the first $$$i$$$ queries.


Sample Inputs:
4 4 8
..**
.*..
*...
...*
1 3
2 3
3 1
2 3
3 4
4 3
2 3
2 2

2 5 5
*...*
*****
1 3
2 2
1 3
1 5
2 3

Sample Outputs:
3
4
4
3
4
5
5
5

2
3
3
3
2

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

def solve():
    (R, C, Q) = map(int, input().split())
    s = []
    for _ in range(R):
        s.append(list(input().strip()))
    t = []
    for i in range(C):
        for j in range(R):
            t.append(s[j][i])
    total = t.count('*')
    current = t[total:].count('*')
    for _ in range(Q):
        (x, y) = map(int, input().split())
        x -= 1
        y -= 1
        now = y * R + x
        if t[now] == '*':
            if now >= total:
                current -= 1
            t[now] = '.'
            total -= 1
            if t[total] == '*':
                current += 1
        else:
            if now >= total:
                current += 1
            t[now] = '*'
            if t[total] == '*':
                current -= 1
            total += 1
        print(current)
solve()

Solution (Python):
from collections import Counter, defaultdict, deque
import bisect
from sys import stdin, stdout
from itertools import repeat, permutations
import math
import heapq
import random
MOD = int(1000000000.0) + 7

def inp(force_list=False):
    re = list(map(int, input().split()))
    if len(re) == 1 and (not force_list):
        return re[0]
    return re

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

def gcd(x, y):
    while y:
        (x, y) = (y, x % y)
    return x

def lcm(x, y):
    return x * y / gcd(x, y)

def qmod(a, b, mod=MOD):
    res = 1
    while b:
        if b & 1:
            res = res * a % mod
        b >>= 1
        a = a * a % mod
    return res

def inv(a):
    return qmod(a, MOD - 2)

def query(x, y):
    print('? %d %d' % (x, y))
    stdout.flush()
    return gcd(11 + x, 11 + y)

def C(n, k):
    return fac[n] * inv(fac[k] * fac[n - k] % MOD) % MOD

def my_main():
    global MOD
    kase = 1
    pans = []
    for _ in range(kase):
        (n, m, q) = inp()
        da = [inst() for i in range(n)]
        nda = []
        sm = 0
        for i in range(m):
            for j in range(n):
                nda.append(1 if da[j][i] == '*' else 0)
                if nda[-1] == 1:
                    sm += 1
        psm = sum(nda[:sm])
        for i in range(q):
            (x, y) = inp()
            x -= 1
            y -= 1
            ox = y * n + x
            if nda[ox]:
                sm -= 1
                psm -= nda[sm]
                if ox < sm:
                    psm -= 1
                nda[ox] = 0
            else:
                if ox < sm:
                    psm += 1
                nda[ox] = 1
                psm += nda[sm]
                sm += 1
            pans.append(str(sm - psm))
    print('\n'.join(pans))
my_main()

Solution (Python):
import sys
input = sys.stdin.readline
write = sys.stdout.write
(n, m, q) = list(map(int, input().split()))
data = []
cnt = 0
for i in range(n):
    data.append(list(input().strip()))
    cnt += data[-1].count('*')
temp = 0
match = 0
for j in range(m):
    if temp == cnt:
        break
    for i in range(n):
        if temp == cnt:
            break
        temp += 1
        if data[i][j] == '*':
            match += 1
for _ in range(q):
    (x, y) = list(map(int, input().split()))
    x -= 1
    y -= 1
    temp = y * n + x + 1
    if data[x][y] == '.':
        data[x][y] = '*'
        if temp <= cnt:
            match += 1
        cnt += 1
        if data[(cnt - 1) % n][(cnt - 1) // n] == '*':
            match += 1
    else:
        if data[(cnt - 1) % n][(cnt - 1) // n] == '*':
            match -= 1
        data[x][y] = '.'
        cnt -= 1
        if temp <= cnt:
            match -= 1
    write(str(cnt - match) + '\n')