代码随想录:开发商购买土地

代码随想录:开发商购买土地

纯铸币题目浪费时间,两个include记一下

#include<climits>//INT_MAX
#include<cmath>//min
#include<iostream>
#include<vector>
#include <climits>
#include <cmath>
using namespace std;

int main()
{
    int a, b;
    cin >> a >> b;

    vector<vector<int>> target(a, vector<int>(b));

    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            cin >> target[i][j];
        }
    }

    // 竖切计算
    vector<int> shu(b, 0);
    for (int i = 0; i < b; i++) {
        for (int j = 0; j < a; j++) {
            shu[i] += target[j][i];
        }
    }

    // 竖切前缀和
    vector<int> shu_sum(b, 0);
    shu_sum[0] = shu[0];
    for (int i = 1; i < b; i++) {
        shu_sum[i] = shu_sum[i - 1] + shu[i];
    }

    // 横切计算
    vector<int> heng(a, 0);
    for (int i = 0; i < a; i++) {
        for (int j = 0; j < b; j++) {
            heng[i] += target[i][j];
        }
    }

    // 横切前缀和
    vector<int> heng_sum(a, 0);
    heng_sum[0] = heng[0];
    for (int i = 1; i < a; i++) {
        heng_sum[i] = heng_sum[i - 1] + heng[i];
    }

    int shu_res = INT_MAX;
    for (int i = 0; i < b - 1; i++) {
        // 计算两部分和的差值
        int left = shu_sum[i];
        int right = shu_sum[b - 1] - left;
        shu_res = min(shu_res, abs(left - right));
    }

    int heng_res = INT_MAX;
    for (int i = 0; i < a - 1; i++) {
        // 计算两部分和的差值
        int top = heng_sum[i];
        int bottom = heng_sum[a - 1] - top;
        heng_res = min(heng_res, abs(top - bottom));
    }

    int res = min(shu_res, heng_res);
    cout << res;

    return 0;
}

posted @ 2024-11-17 15:12  huigugu  阅读(1)  评论(0编辑  收藏  举报