import sys def aktualizuj_mozliwe(plansza, mozliwe, x, y, n, m): """ Aktualizuje zbiór klocków, które można usunąć """ for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0), (0, 0)]: nx, ny = x + dx, y + dy if 1 <= nx <= n and 1 <= ny <= m: if plansza[nx][ny]: if ((nx == 1 or nx == n or not plansza[nx - 1][ny] or not plansza[nx + 1][ny]) or (ny == 1 or ny == m or not plansza[nx][ny - 1] or not plansza[nx][ny + 1])): mozliwe.add((nx, ny)) else: mozliwe.discard((nx, ny)) def zbieranie_klockow(n, m, k, q, klocki, operacje): """ Rozwiązuje zadanie zbierania klocków """ # Tworzymy planszę plansza = [[0] * (m + 2) for _ in range(n + 2)] mozliwe = set() # Ustawiamy początkowe klocki for x, y in klocki: plansza[x][y] = 1 # Znajdujemy początkowe możliwe do usunięcia klocki for x, y in klocki: aktualizuj_mozliwe(plansza, mozliwe, x, y, n, m) wyniki = [len(mozliwe)] # Wykonujemy operacje for x, y in operacje: plansza[x][y] ^= 1 # Dodanie/usunięcie klocka aktualizuj_mozliwe(plansza, mozliwe, x, y, n, m) wyniki.append(len(mozliwe)) return wyniki if __name__ == "__main__": n, m, k, q = map(int, sys.stdin.readline().split()) klocki = [tuple(map(int, sys.stdin.readline().split())) for _ in range(k)] operacje = [tuple(map(int, sys.stdin.readline().split())) for _ in range(q)] wyniki = zbieranie_klockow(n, m, k, q, klocki, operacje) sys.stdout.write("\n".join(map(str, wyniki)) + "\n")
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import sys def aktualizuj_mozliwe(plansza, mozliwe, x, y, n, m): """ Aktualizuje zbiór klocków, które można usunąć """ for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0), (0, 0)]: nx, ny = x + dx, y + dy if 1 <= nx <= n and 1 <= ny <= m: if plansza[nx][ny]: if ((nx == 1 or nx == n or not plansza[nx - 1][ny] or not plansza[nx + 1][ny]) or (ny == 1 or ny == m or not plansza[nx][ny - 1] or not plansza[nx][ny + 1])): mozliwe.add((nx, ny)) else: mozliwe.discard((nx, ny)) def zbieranie_klockow(n, m, k, q, klocki, operacje): """ Rozwiązuje zadanie zbierania klocków """ # Tworzymy planszę plansza = [[0] * (m + 2) for _ in range(n + 2)] mozliwe = set() # Ustawiamy początkowe klocki for x, y in klocki: plansza[x][y] = 1 # Znajdujemy początkowe możliwe do usunięcia klocki for x, y in klocki: aktualizuj_mozliwe(plansza, mozliwe, x, y, n, m) wyniki = [len(mozliwe)] # Wykonujemy operacje for x, y in operacje: plansza[x][y] ^= 1 # Dodanie/usunięcie klocka aktualizuj_mozliwe(plansza, mozliwe, x, y, n, m) wyniki.append(len(mozliwe)) return wyniki if __name__ == "__main__": n, m, k, q = map(int, sys.stdin.readline().split()) klocki = [tuple(map(int, sys.stdin.readline().split())) for _ in range(k)] operacje = [tuple(map(int, sys.stdin.readline().split())) for _ in range(q)] wyniki = zbieranie_klockow(n, m, k, q, klocki, operacje) sys.stdout.write("\n".join(map(str, wyniki)) + "\n") |