Day6 - I - Sticks Problem POJ - 2452

Xuanxuan has n sticks of different length. One day, she puts all her sticks in a line, represented by S1, S2, S3, ...Sn. After measuring the length of each stick Sk (1 <= k <= n), she finds that for some sticks Si and Sj (1<= i < j <= n), each stick placed between Si and Sj is longer than Si but shorter than Sj.

Now given the length of S1, S2, S3, …Sn, you are required to find the maximum value j - i.

Input

The input contains multiple test cases. Each case contains two lines.
Line 1: a single integer n (n <= 50000), indicating the number of sticks.
Line 2: n different positive integers (not larger than 100000), indicating the length of each stick in order.

Output

Output the maximum value j - i in a single line. If there is no such i and j, just output -1.

Sample Input

4
5 4 3 6
4
6 5 4 3

Sample Output

1
-1

思路:求每个点往右的最大值且都不小于他,先想到了单调队列,区间最值就用ST表,整了整发现WA了,发现并不需要两端队列,遍历每一个点找右侧就行了,好像叫单调栈,找到比每个点小的第一个点,在这个区间内找最大点,用二分加速寻找就行了
const int maxm = 5e4+10;

int Max[maxm][20], Min[maxm][20], a[maxm], N;

void init() {
    memset(Max, 0, sizeof(Max)), memset(Min, 0, sizeof(Min));
}

int BisearchMin(int pos) {
    int l = pos+1, r = N, mid, ans = N, k, t;
    while(l <= r) {
        mid = (l + r) >> 1;
        k = log((double)(mid-pos+1)) / log(2.0);
        t = min(Min[pos][k], Min[mid - (1 << k) + 1][k]);
        if(t < a[pos]) {
            ans = mid;
            r = mid - 1;
        } else
            l = mid + 1;
    }
    return ans;
}

int BisearchMax(int l, int r) {
    int k, ans, mid, t, t2;
    k = log((double)(r - l + 1)) / log(2.0);
    t = max(Max[l][k], Max[r - (1<<k)+1][k]);
    while(l <= r) {
        mid = (l + r) >> 1;
        k = log((double)(mid - l + 1)) / log(2.0);
        t2 = max(Max[l][k], Max[mid - (1<<k)+1][k]);
        if(t2 == t) {
            ans = mid;
            r = mid - 1;
        } else
            l = mid + 1;
    }
    return ans;
}

int main() {
    while(scanf("%d", &N) != EOF) {
        init();
        int ans = -1;
        for(int i = 1; i <= N; ++i) {
            scanf("%d", &a[i]);
            Max[i][0] = Min[i][0] = a[i];
        }
        for(int k = 1; (1<<k) <= N; ++k) {
            for(int i = 1; i+(1<<k)-1 <= N; ++i) {
                Max[i][k] = max(Max[i][k-1], Max[i+(1<<(k-1))][k-1]);
                Min[i][k] = min(Min[i][k-1], Min[i+(1<<(k-1))][k-1]);
            }
        }
        for(int i = 1; i <= N; ++i) {
            int r = BisearchMin(i);
            r = BisearchMax(i, r);
            if(i != r)
                ans = max(ans, r - i);
        }
        printf("%d\n", ans);
    }
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/GRedComeT/p/12205035.html
今日推荐