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 3Sample Output
1 -1给定一个长度为n的序列,序列里的元素都不相同,要求找出一对(i,j),i<j,arr[k]>=i&arr[k]<=j,All(i < k < j).然后求最大的j-i差值。
RMQ+二分 先初始化rmq,这里的dp数组存储的是序列的下标。然后枚举每个结束点x,用rmq查询离x点最远的点j,使得max[j,x-1] < x,这里要用到二分,查询区间最值有rmq。找出最远的那个点j后,就要找[j,x-1]区间内值最小的那个下标i,然后x -i就是以x结尾符合条件的最长序列。
AC代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<map>
#include<iomanip>
#include<math.h>
using namespace std;
typedef long long ll;
typedef double ld;
const ll INF=1e18;
const int maxx = 50000 + 10;
int n;
int a[maxx];
int dpmax[maxx][20];
int dpmin[maxx][20];
int mn[maxx];
inline void init_rmq(int a[],int n) ///构建rmq
{
mn[0]=-1;
for(int i = 1; i <= n; ++i)
{
if((i&(i-1))==0)
{
mn[i] = mn[i-1]+1;
}
else
{
mn[i] = mn[i-1];
}
dpmax[i][0] = a[i];
dpmin[i][0] = a[i];
}
for(int j = 1; j <= mn[n]; ++j)
{
for(int i = 1; i+(1<<j)-1 <= n; ++i)
{
dpmax[i][j] = max(dpmax[i][j-1],dpmax[i+(1<<(j-1))][j-1]);
dpmin[i][j] = min(dpmin[i][j-1],dpmin[i+(1<<(j-1))][j-1]);
}
}
}
inline int max_rmq(int l,int r) //查询区间最大值
{
int k = mn[r-l+1];
return max(dpmax[l][k],dpmax[r-(1<<k)+1][k]);
}
inline int min_rmq(int l,int r) //查询区间最小值
{
int k = mn[r-l+1];
return min(dpmin[l][k],dpmin[r-(1<<k)+1][k]);
}
int main()
{
while(scanf("%d",&n)==1)
{
for(int i = 1; i <= n; ++i)
{
scanf("%d",&a[i]);
}
init_rmq(a,n);
int ans = -1;
for(int i = 1; i <= n; ++i)
{
int l = i;
int r = n+1;
while(l+1 != r)
{
int mid = (l+r)>>1;
if(min_rmq(i,mid) == a[i])
{
l = mid;
}
else
{
r = mid;
}
}
int ll = i;
int rr = l;
if(l != i)
{
int temp = max_rmq(ll,rr);
while(ll+1 != rr)
{
int mid = (ll+rr)>>1;
if(max_rmq(i,mid) < temp)
{
ll = mid;
}
else
{
rr = mid;
}
}
}
if(rr-i>ans)
ans = rr-i;
}
if(ans)
printf("%d\n",ans);
else
printf("-1\n");
}
return 0;
}