解題思路
枚舉上、下邊界,將其中每欄的值加總成一維陣列。任一子矩形對應這個陣列的一段連續子陣列。
掃描一維前綴和P,某段和為P−Q。要使它≤K又盡量大,需找先前前綴和中最小的Q≥P−K。C++以有序集合lower_bound查詢;Python以壓縮全部前綴和加Fenwick計數求後繼。
每個前綴只能在查詢後才插入,確保段非空;答案初始0代表可不選任何區域。若答案達K即可直接結束。負值使一般正數滑動視窗失效。
O(M²N log N)時間、O(MN+N)空間;Python read().split()另O(MN)輸入詞。
Step-by-step animation
示例:陣列[2,−1,4],K=4,前綴0、2、1、5。
步驟 1 / 3
一列例
陣列[2,−1,4],K=4,前綴0、2、1、5。
0
2
1
5
- 答案初值
- 0
#include <bits/stdc++.h>
using namespace std;
int main() {
long long K;
int M, N;
cin >> K >> M >> N;
vector<vector<long long>> a(M, vector<long long>(N));
for (auto &r : a)
for (auto &x : r)
cin >> x;
long long ans = 0;
for (int top = 0; top < M; top++) {
vector<long long> b(N);
for (int bot = top; bot < M; bot++) {
for (int j = 0; j < N; j++)
b[j] += a[bot][j];
set<long long> s = {0};
long long p = 0;
for (long long x : b) {
p += x;
auto it = s.lower_bound(p - K);
if (it != s.end())
ans = max(ans, p - *it);
if (ans == K) {
cout << ans << '\n';
return 0;
}
s.insert(p);
}
}
}
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。