Description
Now we define that:
A(j)={i|0<i<j&&a[i]<a[j]}
Here a is an array with n element(1<=n<=1000000);
And then we define a function f that:
int f(int j){
if(A(j) is not empty) return max( A(j) );
else return -1;
}
Input
The first line contain an integer n(1<=n<=1000000),the size of the array a.
The second line contain n integers describe the array a.
The third line is an integer m(1<=m<=1000000),the number of the query.
And then follow m lines,each line is an integer j(1<=j<=n).
Output
For each query j,output a[f(j)] if f(j)>=1,Otherwise output -1 instead.
Sample Input
3
1 2 3
3
1
2
3
Sample Output
-1
1
2
单调DP,用另一数组记录下a[f(i)],可用stack实现。
#include<iostream>
#include<stack>
#include<cstdio>
using namespace std;
#define N 1000005
int a[N],b[N];
int main()
{
int n,m,i,temp,x;
stack<int> S;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(S.empty())
{
b[i]=-1;
S.push(a[i]);
}
else
{
temp=S.top();
if(temp<a[i])
{
b[i]=temp;
S.push(a[i]);
}
else
{
S.pop();
while(!S.empty())
{
temp=S.top();
if(temp<a[i])
{
b[i]=temp;
S.push(a[i]);
break;
}
else
S.pop();
}
if(S.empty())
{
b[i]=-1;
S.push(a[i]);
}
}
}
}
scanf("%d",&m);
while(m--)
{
scanf("%d",&x);
printf("%d\n",b[x-1]);
}
return 0;
}