[POJ2452] Sticks Problem

Description

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

Source

POJ Monthly,static

题解

这题的正解是(ST)算法,先解释一下题意

给定一个区间,要在此区间内找到一个满足下列条件的最长区间,并求出此区间右端点-左端点的值(为0的话输出(-1)):

  • 区间内的所有数都大于区间的第一个数

  • 区间内的所有数都小于区间的最后一个数

代码其实并不难,结合注释比较容易懂:

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;

const int N=60000;
int n,a[N],f1[N][25],f2[N][25];
//f1,f2数组记录的是一个下标

int MIN(int id1,int id2)
{
    if(a[id1]<a[id2]) return id1;
    return id2;
}

int MAX(int id1,int id2)
{
    if(a[id1]>a[id2]) return id1;
    return id2;
}

void ST()
{
    for(int i=1;i<=n;++i) f1[i][0]=f2[i][0]=i;
    int t=(int)(log(n*1.0)/log(2.0));
    for(int i=1;i<=t;++i)
        for(int j=1;j<=n-(1<<i)+1;++j)
            f1[j][i]=MIN(f1[j][i-1],f1[j+(1<<(i-1))][i-1]),
            f2[j][i]=MAX(f2[j][i-1],f2[j+(1<<(i-1))][i-1]);
}

int MIN_ID(int l,int r)
{
    int t=(int)(log((r-l+1)*1.0)/log(2.0));
    return MIN(f1[l][t],f1[r-(1<<t)+1][t]);
}

int MAX_ID(int l,int r)
{
    int t=(int)(log((r-l+1)*1.0)/log(2.0));
    return MAX(f2[l][t],f2[r-(1<<t)+1][t]);
}

int Find(int id,int l,int r)//二分求最长的符合条件①的区间
{
    int m;
    while(l<=r)
    {
        if(l==r) return l;
        m=(l+r)>>1;
        if(a[id]<a[MIN_ID(l,m)]) l=m+1;
        else r=m;
    }
}

void Solve()
{
    int Ans=0,rr,r;
    for(int i=1;i<n-Ans;++i)
    {
        rr=Find(i,i+1,n),r=MAX_ID(i,rr);//利用条件②来截取区间
        if(a[r]>a[i]) Ans=max(Ans,r-i);
    }
    printf("%d
",Ans?Ans:-1);
}

int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=1;i<=n;++i) scanf("%d",&a[i]);
        ST(),Solve();
    }
    return 0;
}
原文地址:https://www.cnblogs.com/hihocoder/p/12354879.html