https://www.acmicpc.net/problem/17822
def rotate(x, to_left, k):
for i in range(1, n+1):
if i % x != 0:
continue
front = board[i][m-k:]
back = board[i][:m-k]
if to_left:
front = board[i][k:]
back = board[i][:k]
board[i] = front + back
def change():
to_delete = find()
if to_delete:
for i, j in to_delete:
board[i][j] = float('inf')
else:
summ, count = 0, 0
for i in range(1, n+1):
for j in range(m):
if board[i][j] == float('inf'):
continue
summ += board[i][j]
count += 1
if count == 0:
return
for i in range(1, n+1):
for j in range(m):
if summ / count > board[i][j]:
board[i][j] += 1
elif summ / count < board[i][j]:
board[i][j] -= 1
def find():
to_delete = set()
# check rows
for i in range(1, n+1):
for j in range(m):
if board[i][j] == float('inf') or board[i][(j+1)%m] == float('inf'):
continue
if board[i][j] == board[i][(j+1)%m]:
to_delete.add((i, j))
to_delete.add((i, (j+1)%m))
# check cols
for j in range(m):
for i in range(1, n):
if board[i][j] == float('inf') or board[i+1][j] == float('inf'):
continue
if board[i][j] == board[i+1][j]:
to_delete.add((i, j))
to_delete.add((i+1, j))
return to_delete
def get_sum():
summ = 0
for i in range(1, n+1):
for j in range(m):
if board[i][j] == float('inf'):
continue
summ += board[i][j]
return summ
import sys
read = sys.stdin.readline
n, m, t = map(int, read().split())
board = [[] for _ in range(n+1)]
for i in range(1, n+1):
board[i] = list(map(int, read().split()))
commands = [list(map(int, read().split())) for _ in range(t)]
for x, d, k in commands:
rotate(x, d, k)
change()
print(get_sum())