An Easy Problem

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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值