a784中等列壓縮與非空 Kadane
CPE:Maximum Sum (UVa 108)
將最大子矩形化為多次最大連續子陣列。
解題思路
固定上邊界 top,將下邊界 bottom 逐列往下擴張,維護每一欄在 top 到 bottom 之間的總和。任一左右連續區間在這個壓縮陣列上的和,正好就是對應矩形的總和,因此只需在每對上下邊界執行一次 Kadane。
Kadane 維護以目前欄結尾的最佳非空區間:cur=max(x,cur+x),再更新全域最大值。初始化使用第一個元素而不是 0,才能處理全負矩陣。總共有 O(N²) 對列邊界,每次 O(N),把四邊枚舉的成本降到 O(N³)。本地題目只有一個矩陣,讀滿 N² 個值即可。
Step-by-step animation
示意:矩陣 [-2,3;4,-1]
步驟 1 / 3
只看第一列
壓縮值 −2、3,最佳區間為 3。
-2
3
- top,bottom
- 0,0
- best
- 3
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
if (!(cin >> n))
return 0;
vector<vector<int>> a(n, vector<int>(n));
for (auto &row : a)
for (int &x : row)
cin >> x;
int best = a[0][0];
for (int top = 0; top < n; ++top) {
vector<int> sum(n, 0);
for (int bottom = top; bottom < n; ++bottom) {
for (int c = 0; c < n; ++c)
sum[c] += a[bottom][c];
int cur = sum[0];
best = max(best, cur);
for (int c = 1; c < n; ++c) {
cur = max(sum[c], cur + sum[c]);
best = max(best, cur);
}
}
}
cout << best << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。