1941E - Rudolf and k Bridges - CodeForces Solution


binary search data structures dp two pointers

Please click on ads to support us..

Python Code:

from heapq import heappop, heappush
t = int(input())

for _ in range(t):
    n, m, k, d = list(map(int, input().split()))

    grid = [[0 for i in range(m)] for j in range(n)]
    for i in range(n):
        a = list(map(int, input().split()))
        for j in range(m):
            grid[i][j] = a[j]
    
    row = []
    for r in range(n):

                heap = [[0, 0]]
        dp = [0 for i in range(m)]
        for c in range(1, m):
            while heap and c - heap[0][1] - 1 > d:
                heappop(heap)
            dp[c] = heap[0][0] + grid[r][c] + 1
            heappush(heap, [heap[0][0] + grid[r][c] + 1, c])
            
        
        

                heap = [[0, m - 1]]
        dp1 = [0 for i in range(m)]
        for c in range(m - 2, -1, -1):
            while heap and heap[0][1] - c - 1 > d:
                heappop(heap)
            dp1[c] = heap[0][0] + grid[r][c] + 1
            heappush(heap, [heap[0][0] + grid[r][c] + 1, c])
        
        ans = dp[-1] + 2
        for i in range(min(m, d + 2)):
            ans = min(ans, dp1[i] + 2, dp[m - i - 1] + 2)
        
        row.append(ans)

        
            ans = sum(row[:k])
    total = ans
    for i in range(k, n):
        total += row[i] - row[i - k]
        ans = min(ans, total)
    
    print(ans)
    


Comments

Submit
0 Comments
More Questions

1702D - Not a Cheap String
1714F - Build a Tree and That Is It
1703F - Yet Another Problem About Pairs Satisfying an Inequality
610A - Pasha and Stick
1200A - Hotelier
1091A - New Year and the Christmas Ornament
1352B - Same Parity Summands
1102A - Integer Sequence Dividing
630B - Moore's Law
1004A - Sonya and Hotels
1680B - Robots
1690A - Print a Pedestal (Codeforces logo)
1295A - Display The Number
1077A - Frog Jumping
1714G - Path Prefixes
1369C - RationalLee
289B - Polo the Penguin and Matrix
1716A - 2-3 Moves
1670B - Dorms War
1716B - Permutation Chain
987A - Infinity Gauntlet
1676G - White-Black Balanced Subtrees
1716D - Chip Move
1352F - Binary String Reconstruction
1487B - Cat Cycle
1679C - Rooks Defenders
56A - Bar
1694B - Paranoid String
35A - Shell Game
1684A - Digit Minimization