목차

체스판 다시 칠하기 2

ps
링크acmicpc.net/…
출처BOJ
문제 번호25682
문제명체스판 다시 칠하기 2
레벨골드 5
분류

누적합

시간복잡도O(N*M)
인풋사이즈N<=2000, M<=2000
사용한 언어Python
제출기록192740KB / 2200ms
최고기록2200ms
해결날짜2022/11/17
태그

[단계]누적 합

풀이

코드

"""Solution code for "BOJ 25682. 체스판 다시 칠하기 2".

- Problem link: https://www.acmicpc.net/problem/25682
- Solution link: http://www.teferi.net/ps/problems/boj/25682

Tags: [prefix sum]
"""

import sys


def main():
    # pylint: disable=unused-variable
    N, M, K = [int(x) for x in sys.stdin.readline().split()]
    board = [sys.stdin.readline().rstrip() for _ in range(N)]

    prefix_sum = [[0] * (M + 1)]
    for row, psum_row_prev, target in zip(board, prefix_sum, 'BW' * N):
        psum_row_cur = [0]
        rsum = 0
        for ch, ps in zip(row, psum_row_prev[1:]):
            rsum += ch == target
            target = 'B' if target == 'W' else 'W'
            psum_row_cur.append(ps + rsum)
        prefix_sum.append(psum_row_cur)

    answer = K * K
    for beg, end in zip(prefix_sum, prefix_sum[K:]):
        for bb, be, eb, ee in zip(beg, beg[K:], end, end[K:]):
            s = ee - be - eb + bb
            answer = min(answer, s, K * K - s)

    print(answer)


if __name__ == '__main__':
    main()