枚举横着切还是竖着切,然后切多少,用二维前缀和加速即可。
#include<bits/stdc++.h> #define int long long #define double long double #define x first #define y second using namespace std; typedef long long LL; typedef long long ll; typedef pair<int, int> PII; const int N = 3e5 + 10; const int M = 1e3 + 10; int mod = 1e9 + 7; int a[M][M]; int ask(int x1, int y1, int x2, int y2) { return a[x2][y2] - a[x1 - 1][y2] - a[x2][y1 - 1] + a[x1 - 1][y1 - 1]; } void solve() { int n; cin >> n; int m; cin >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> a[i][j]; a[i][j] += a[i - 1][j] + a[i][j - 1] - a[i - 1][j - 1]; } } int minn = 1e18; for (int i = 1; i <= n; i++) minn = min(minn, abs(ask(1, 1, i, m) - ask(i + 1, 1, n, m))); for (int i = 1; i <= m; i++) minn = min(minn, abs(ask(1, 1, n, i) - ask(1, i + 1, n, m))); cout << minn << "\n"; } signed main() { ios::sync_with_stdio(false); cin.tie(0), cout.tie(0); int _; _ = 1; //cin>>_; while (_--) { solve(); } }