解題思路
固定上、下兩列,把每欄壓成分數和與標記數,問題變成一維非空區間恰 K 標記、和最大。
掃描右端,令分數前綴 S、標記前綴 C。需要以前出現 C-K 的位置,並選其中最小分數前綴,得到 S-minPrefix[C-K]。
查詢後才加入目前前綴,確保非空;枚舉所有列對便涵蓋全部矩形。可先轉置令列數較小。
時間 O(min(h,w)² max(h,w)),空間 O(hw)。
Step-by-step animation
教學例子:範例取第二列,分數 1、5、-2,標記 0、0、1。
步驟 1 / 3
步驟 1
範例取第二列,分數 1、5、-2,標記 0、0、1。
1
5
-2
- 狀態
- K=1
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int h, w, K;
cin >> h >> w >> K;
vector<vector<long long>> a(h, vector<long long>(w));
for (auto &r : a)
for (auto &x : r)
cin >> x;
vector<string> b(h);
for (auto &s : b)
cin >> s;
if (h > w) {
vector<vector<long long>> c(w, vector<long long>(h));
vector<string> d(w, string(h, '0'));
for (int i = 0; i < h; i++)
for (int j = 0; j < w; j++) {
c[j][i] = a[i][j];
d[j][i] = b[i][j];
}
a.swap(c);
b.swap(d);
swap(h, w);
}
const long long NEG = -(1LL << 60);
long long ans = NEG;
for (int top = 0; top < h; top++) {
vector<long long> s(w);
vector<int> cnt(w);
for (int bot = top; bot < h; bot++) {
for (int j = 0; j < w; j++) {
s[j] += a[bot][j];
cnt[j] += b[bot][j] - '0';
}
unordered_map<int, long long> mn;
mn[0] = 0;
long long pre = 0;
int c = 0;
for (int j = 0; j < w; j++) {
pre += s[j];
c += cnt[j];
if (mn.count(c - K))
ans = max(ans, pre - mn[c - K]);
if (!mn.count(c) || pre < mn[c])
mn[c] = pre;
}
}
}
if (ans == NEG)
cout << "IMPOSSIBLE\n";
else
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。