7장 분할 정복 2

Updated:
1 minute read

7.4 문제: 울타리 잘라내기 (문제 ID: FENCE, 난이도: 중)

문제 자세히 보기

#include <iostream>
#include <algorithm>

using namespace std;

int fences[20000];
int maxArea(int left, int right) {
    if(left == right) return fences[left];

    int mid = (left + right) / 2;
    int area = max(maxArea(left, mid), maxArea(mid + 1, right));

    int lo = mid;
    int hi = mid + 1;
    int h = min(fences[lo], fences[hi]);
    area = max(area, h * 2);
    while(left < lo || hi < right) {
        if(hi < right && (left == lo || fences[lo - 1] < fences[hi + 1]))
            h = min(h, fences[++hi]);
        else
            h = min(h, fences[--lo]);

        area = max(area, h * (hi - lo + 1));
    }

    return area;
}

int main() {
    ios_base::sync_with_stdio(false);
    int C;
    cin >> C;
    while(C--) {
        int N;
        cin >> N;
        for(int i = 0; i < N; ++i) cin >> fences[i];

        cout << maxArea(0, N - 1) << endl;
    }

    return 0;
}
Back to top ↑

Leave a comment