ARC063F Snuke's Coloring 2 [單調棧+線段樹]

Description:
二維平面上有一些點,我們可以把過這個點且平行於座標軸的直線和邊框夾成的區域塗黑。問最後剩下白色區域的最大周長(顯然是一個矩形)。


Solution:
我們可以發現這個矩形肯定經過x=w2y=h2 。那麼我們可以考慮枚舉上下邊界,這樣可以做到O(n2) 。然後考慮優化這個過程。對於一個上邊界,我們希望取到最大值。
我們維護一個線段樹,維護每個位置的寬度和距離當前枚舉點的長度。假設當前經過x=w2 ,那麼自然希望從這條直線儘量向兩邊拓展,最大寬度也就是距離這條線左右兩側最近的兩個點的距離,那麼維護兩個單調棧即可。


#include <bits/stdc++.h>
#define x first
#define y second 
using namespace std;

typedef pair<int, int> PII;

const int maxn = 3e5 + 5;

int w, h, n, ans;

int mx[maxn * 4], tag[maxn * 4];

PII a[maxn], b[maxn], p[maxn];

void pushdown(int x) {
    tag[x << 1] += tag[x];
    tag[x << 1 | 1] += tag[x];
    mx[x << 1] += tag[x];
    mx[x << 1 | 1] += tag[x];
    tag[x] = 0;
}

void update(int l, int r, int x, int a, int b, int d) {
    if(l > b || r < a) {
        return;
    }
    if(l >= a && r <= b) {
        tag[x] += d;
        mx[x] += d;
        return;
    }
    pushdown(x);
    int mid = (l + r) >> 1;
    update(l, mid, x << 1, a, b, d);
    update(mid + 1, r, x << 1 | 1, a, b, d);
    mx[x] = max(mx[x << 1], mx[x << 1 | 1]);
}

void solve() {
    memset(mx, 0, sizeof(mx));
    memset(tag, 0, sizeof(tag));

    sort(p + 1, p + n + 1);

    int l = 0, r = 0;

    for(int i = 1; i < n; ++i) {
        if(p[i].y <= h / 2) {
            int nxt = i - 1;
            while(l && p[i].y > a[l].y) {
                update(1, n, 1, a[l].x, nxt, a[l].y - p[i].y);
                nxt = a[l].x - 1;
                --l;
            }
            if(nxt != i - 1) {
                a[++l] = PII(nxt + 1, p[i].y);
            }
        } else {
            int nxt = i - 1;
            while(r && p[i].y < b[r].y) {
                update(1, n, 1, b[r].x, nxt, p[i].y - b[r].y);
                nxt = b[r].x - 1;
                --r;
            }
            if(nxt != i - 1) {
                b[++r] = PII(nxt + 1, p[i].y);
            }
        }

        a[++l] = PII(i, 0);
        b[++r] = PII(i, h);

        update(1, n, 1, i, i, h - p[i].x);

        ans = max(ans, p[i + 1].x + mx[1]); 

    }
}

int main() {

    scanf("%d%d%d", &w, &h, &n);

    for(int i = 1; i <= n; ++i) {
        scanf("%d%d", &p[i].x, &p[i].y);
    }

    p[++n] = PII(0, 0);
    p[++n] = PII(w, h);

    solve();
    for(int i = 1; i <= n; ++i) {
        swap(p[i].x, p[i].y);
    }

    swap(w, h);

    solve();

    printf("%d\n", ans << 1);

    return 0;
}
發佈了102 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章