维护好二维前缀和sum后,所有可能的 sum[i][m] 和 sum[n][i] 就是小美拥有的,而 sum[n][m] 减去小美拥有的就是小团拥有的,遍历所有可能性,维护好最小的二者的差的绝对值即可
#include <bits/stdc++.h> using namespace std; #define int long long int __t = 1, n, m; void solve() { cin >> n >> m; vector<vector<int>> a(n + 1, vector<int>(m + 1, 0)), sum(n + 1, vector<int>(m + 1, 0)); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { cin >> a[i][j]; sum[i][j] = a[i][j] + sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1]; } int ans = sum[n][m]; for (int i = 1; i < n; i++) ans = min(abs(sum[n][m] - 2 * sum[i][m]), ans); for (int i = 1; i < m; i++) ans = min(abs(sum[n][m] - 2 * sum[n][i]), ans); cout << ans << '\n'; } int32_t main() { #ifdef ONLINE_JUDGE ios::sync_with_stdio(false); cin.tie(0); #endif // cin >> __t; while (__t--) solve(); return 0; }