[CodeForces] F. Color Rows and Columns

Problem Link

 

Based on initial observation, it seems that greedily pick the smallest row / column length works. But the last example test case outputs 35 while greedy gives 36. 

 

How you should go from there:

1. check if your greedy implementation is correct. It was, in this case.

2. if no implementation bugs, then maybe greedy does not work, think dp.

3. the input constraint implies a dp of O(N * K * K) is fast enough.

 

dp[i][j]: min cost to get score j from [1, i] rectangles;

dp[i][j] = min {dp[i - 1][j - currTake] + cost[i][currTaken]}; loop on i and j, for a given score j the current rectangle i, we can take [0, j] scores from rectangle i. 

 

The remaining work is to precompute cost[i][x], the min cost of getting score x from rectangle i. 

For a given score x, it is a combination of getting score from completing a row or column. 

so we iterate over a rectangle's width and height to compute cost[i][x]. 

Don't forget to deduct the intersection between completed rows and columns as we do not need to paint these cells twice.

 

            int[][] cost = new int[n + 1][k + 1];
            for(int i = 0; i < cost.length; i++) {
                Arrays.fill(cost[i], Integer.MAX_VALUE);
                cost[i][0] = 0;
            }
            for(int i = 1; i <= n; i++) {
                for(int r = 0; r <= x[i][0]; r++) {
                    for(int c = 0; c <= x[i][1]; c++) {
                        if(r + c <= k) {
                            cost[i][r + c] = min(cost[i][r + c], r * x[i][1] + c * x[i][0] - r * c);
                        }
                    }
                }
            }

 

posted @ 2024-08-14 23:46  Review->Improve  阅读(67)  评论(0编辑  收藏  举报