KPLANK - Bán dừa

Tác giả: RR

Ngôn ngữ: C++

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <string>
#include <deque>
#include <complex>
#include <sstream>
#include <iomanip>

#define FOR(i,a,b) for(int i=(a),_b=(b); i<=_b; i++)
#define FORD(i,a,b) for(int i=(a),_b=(b); i>=_b; i--)
#define REP(i,a) for(int i=0,_a=(a); i<_a; i++)
#define ll long long
#define F first
#define S second
#define PB push_back
#define MP make_pair
using namespace std;

const double PI = acos(-1.0);

int INP,AM;
#define BUFSIZE (1<<10)
char BUF[BUFSIZE+1], *inp=BUF;
#define GETCHAR(INP) { \
    if(!*inp) { \
        fread(BUF,1,BUFSIZE,stdin); \
        inp=BUF; \
    } \
    INP=*inp++; \
}
#define DIG(a) (((a)>='0')&&((a)<='9'))
#define GN(j) { \
    AM=0;\
    GETCHAR(INP); while(!DIG(INP) && INP!='-') GETCHAR(INP);\
    if (INP=='-') {AM=1;GETCHAR(INP);} \
    j=INP-'0'; GETCHAR(INP); \
    while(DIG(INP)){j=10*j+(INP-'0');GETCHAR(INP);} \
    if (AM) j=-j;\
}

int n, st[1000111], a[1000111], l[1000111], r[1000111], top;

int main() {
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
    GN(n); FOR(i,1,n) GN(a[i]);
    top = 0; st[0] = 0;
    FOR(i,1,n) {
        while (top && a[st[top]] >= a[i]) top--;
        l[i] = st[top] + 1;
        st[++top] = i;
    }
    top = 0; st[0] = n+1;
    FORD(i,n,1) {
        while (top && a[st[top]] >= a[i]) top--;
        r[i] = st[top] - 1;
        st[++top] = i;
    }
    int res = 0, u;
    FOR(i,1,n) {
        u = r[i] - l[i] + 1;
        if (u < a[i]) continue;
        res = max(res, min(u, a[i]));
    }
    cout << res;
    return 0;
}

Download