codeforces1581C Portal(线性DP/前缀和)

题目链接:codeforces 1581C

思路:

定义 dp[i] 为前 i − 1 i-1 i1 列最小的花费。枚举时先枚举上下边,在对列 DP。因为第 k k k 列可能是边界,也可能在后面的过程中变成中间的部分,所以每次单独计算,而不算在 dp[i] 里面。

参考代码:

#include <iostream>
#include <cstring>
using namespace std;
const int N = 550;
int maze[N][N];
int tot0[N][N], tot1[N][N];
int dp[N];
int count0(int i, int j, int k) {
    return tot0[j][k] - tot0[i-1][k];
}
int count1(int i, int j, int k) {
    return tot1[j][k] - tot1[i-1][k];
}
int main() {
    int t; cin >> t;
    while (t--) {
        memset(tot0, 0, sizeof(tot0)); memset(tot1, 0, sizeof(tot1));
        int n, m; cin >> n >> m;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                char c; cin >> c;
                maze[i][j] = c - '0';
                tot0[i][j] = tot0[i-1][j] + !maze[i][j];
                tot1[i][j] = tot1[i-1][j] + maze[i][j];
            }
        }
        int ans = 0x3f3f3f3f;
        for (int i = 1; i <= n; i++) {
            for (int j = i+4; j <= n; j++) {
                memset(dp, 0x3f, sizeof(dp));
                for (int k = 4; k <= m; k++) {
                    int cost = count0(i+1, j-1, k-3) + !maze[i][k-2] + !maze[i][k-1] + !maze[j][k-2] + !maze[j][k-1] + count1(i+1, j-1, k-2) + count1(i+1, j-1, k-1);
                    dp[k] = min(cost, dp[k-1] + count1(i+1, j-1, k-1) + !maze[i][k-1] + !maze[j][k-1]);
                    ans = min(ans, dp[k] + count0(i+1, j-1, k));
                }
            }
        }
        cout << ans << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值