a301困難直方圖最大矩形與四方向前綴最佳值

TOI 2026/06 潛力組:作物種植 II

在線性網格時間內求一個或恰好兩個不重疊的全 1 矩形。

前往題目練習 →回報教學錯誤時間 O(HW),空間 O(HW+H+W)。H、W≤2000;Python 用 bytes 儲存每列,避免將四百萬格全部存成 Python 整數物件。

解題思路

先求每個方向前綴區域內,最大全 1 矩形的面積。由上往下掃描時,各欄高度記錄連續 1 的格數,每列用單調堆疊求直方圖最大矩形。高度下降時彈出柱子,其左右最近較矮柱限定了可延展寬度;每根柱子至多入堆疊、出堆疊各一次。Python 以 (高度,最左位置) 合併相同高度,省去同高矩形的重複計算。累計截至該列的最佳面積,得到 top;反向掃描得 bottom,以欄為主軸再做兩次得 left、right。

兩個不共用格子的軸對齊矩形,其列區間或欄區間至少一組互不相交,否則兩個投影都相交就會共用格子。所以它們必能被某條水平或垂直格線分開。枚舉水平切線,合併 top[r]+bottom[r+1],垂直切線則合併 left[c]+right[c+1]。兩側面積都要大於 0,才能符合恰好兩個非空矩形;K=1 直接取全圖最大矩形。這涵蓋所有合法兩矩形,也不會把有重疊的矩形相加。

Step-by-step animation

公開範例以第 2、3 欄間的垂直線分開

回報動畫錯誤
步驟 1 / 3

由上而下的高度

第 2 列的高度為 2、2、0、2,最大直方圖矩形為左側 2×2。

2
2
0
2
top[2]
4
矩形
列1..2、欄1..2

Reference solution

回報程式錯誤

完整程式

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
vector<int> prefixes(const vector<vector<unsigned char>> &a, bool columns, bool backwards) {
    int h = a.size(), w = a[0].size(), rows = columns ? w : h, cols = columns ? h : w;
    vector<int> height(cols + 1), ans(rows), st;
    int best = 0;
    for (int step = 0; step < rows; step++) {
        int r = backwards ? rows - 1 - step : step;
        for (int c = 0; c < cols; c++) {
            bool one = columns ? a[c][r] : a[r][c];
            height[c] = one ? height[c] + 1 : 0;
        }
        st.clear();
        for (int c = 0; c <= cols; c++) {
            while (!st.empty() && height[st.back()] >= height[c]) {
                int x = st.back();
                st.pop_back();
                int left = st.empty() ? 0 : st.back() + 1;
                best = max(best, height[x] * (c - left));
            }
            st.push_back(c);
        }
        ans[r] = best;
    }
    return ans;
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int h, w, k;
    cin >> h >> w >> k;
    vector<vector<unsigned char>> a(h, vector<unsigned char>(w));
    for (auto &row : a)
        for (auto &x : row) {
            int v;
            cin >> v;
            x = v;
        }
    auto top = prefixes(a, false, false);
    if (k == 1) {
        cout << top.back() << '\n';
        return 0;
    }
    auto bottom = prefixes(a, false, true), left = prefixes(a, true, false),
         right = prefixes(a, true, true);
    int ans = 0;
    for (int r = 0; r + 1 < h; r++)
        if (top[r] && bottom[r + 1])
            ans = max(ans, top[r] + bottom[r + 1]);
    for (int c = 0; c + 1 < w; c++)
        if (left[c] && right[c + 1])
            ans = max(ans, left[c] + right[c + 1]);
    cout << ans << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多