Strange Game On Matrix (Codeforces 873C)
Tags: Greedy, two pointers

Ivan is playing a strange game.He has a matrix a with n rows and m columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows:  Initially Ivan's score is 0;  In each column, Ivan will find the topmost 1 (that is, if the current column is j, then he will find minimum i such that ai, j = 1). If there are no 1's in the column, this column is skipped;  Ivan will look at the next min(k, n - i + 1) elements in this column (starting from the element he found) and count the number of 1's among these elements. This number will be added to his score. Of course, Ivan wants to maximize his score in this strange game. Also he doesn't want to change many elements, so he will replace the minimum possible number of ones with zeroes. Help him to determine the maximum possible score he can get and the minimum possible number of replacements required to achieve that score.

Input: The first line contains three integer numbers n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100).Then n lines follow, i-th of them contains m integer numbers — the elements of i-th row of matrix a. Each number is either 0 or 1.

Output: Print two numbers: the maximum possible score Ivan can get and the minimum number of replacements required to get this score.

Note: In the first example Ivan will replace the element a1, 2.

Sample Inputs:
4 3 2
0 1 0
1 0 1
0 1 0
1 1 1

3 2 1
1 0
0 1
0 0

Sample Outputs:
4 1

2 0

Solution (Python):
(n, m, k) = map(int, input().split())
a = []
for _ in range(n):
    a.append(list(map(int, input().split())))
total = 0
count = 0
for col in range(m):
    b = [0] * n
    b[0] = a[0][col]
    for row in range(1, n):
        b[row] = b[row - 1] + a[row][col]
    maxSum = 0
    chg = 0
    for row in range(n):
        if a[row][col] == 0:
            continue
        s = b[row - 1] if row > 0 else 0
        f = b[row + k - 1] if row + k - 1 <= n - 1 else b[n - 1]
        sum_val = f - s
        if sum_val > maxSum:
            chg = s
            maxSum = sum_val
    total += maxSum
    count += chg
print(total, count)

Solution (Python):
(n, m, k) = map(int, input().split())
(s, c) = (0, 0)
R = [list(map(int, input().split())) for i in range(n)]
for i in zip(*R):
    (a, b) = (0, 0)
    for j in range(n - k + 1):
        (f, h) = (sum(i[j:j + k]), sum(i[:j]))
        if f > a:
            (a, b) = (f, h)
    s += a
    c += b
print(s, c, end=' ')

Solution (Python):
(n, m, k) = map(int, input().split())
(s, c) = (0, 0)
R = [list(map(int, input().split())) for i in range(n)]
for i in zip(*R):
    (a, b) = (0, 0)
    for j in range(n - k + 1):
        (f, h) = (sum(i[j:j + k]), sum(i[:j]))
        if f > a:
            (a, b) = (f, h)
    s += a
    c += b
print(s, c, end=' ')