文章

242

粉丝

165

获赞

437

访问

229.0k

头像
矩阵相邻元素差值和 题解:
P813
发布于 2026年3月
阅读数 641

#include <bits/stdc++.h>
using namespace std;

const int INF = 1e9;

int n, m, c, d;
vector<vector<int>> a;
int ans = INF;

// 处理当前选中的行组合
void process_rows(const vector<int>& rows) {
    vector<int> vert(m, 0);
    // 计算每列的垂直代价
    for (int j = 0; j < m; ++j) {
        for (int i = 0; i < c - 1; ++i) {
            vert[j] += abs(a[rows[i]][j] - a[rows[i+1]][j]);
        }
    }

    // 计算任意两列的水平代价 cost[j][k] (j < k)
    vector<vector<int>> cost(m, vector<int>(m, 0));
    for (int j = 0; j < m; ++j) {
        for (int k = j + 1; k < m; ++k) {
            int s = 0;
            for (int r : rows) {
                s += abs(a[r][j] - a[r][k]);
            }
            cost[j][k] = s;
        }
    }

    // 一维DP优化:dp_prev 表示选 k-1 列的状态
    vector<int> dp_prev(m, INF);
    for (int j = 0; j < m; ++j) {
        dp_prev[j] = vert[j]; // 选1列时,只有垂直代价
    }

    for (int k = 2; ...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发