题目描述
给出一个长度为N的整数数组A,对于每一个数组元素,如果他后面存在大于等于该元素的数,则这两个数可以组成一对。每个元素和自己也可以组成一对。例如:{5, 3, 6, 3, 4, 2},可以组成11对,如下(数字为下标):
(0,0), (0, 2), (1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (3, 3), (3, 4), (4, 4), (5, 5)。其中(1, 4)是距离最大的一对,距离为3。
收起
输入
第1行:1个数N,表示数组的长度(2 <= N <= 50000)。 第2 - N + 1行:每行1个数,对应数组元素Ai(1 <= Ai <= 10^9)。输出
输出最大距离。输入样例
6 5 3 6 3 4 2输出样例
3单调栈随便模拟一下
AC代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<stack>
#include<iomanip>
#include<math.h>
using namespace std;
typedef long long ll;
typedef double ld;
int n,i,j;
struct node
{
int id,v;
};
stack<node>sq,q;
int main()
{
while(~scanf("%d", &n))
{
while(!sq.empty())
{
sq.pop();
}
int x;
int ans=0;
node a;
for(i=1; i<=n; ++i)
{
scanf("%d",&x);
a.id=i;
a.v=x;
if(sq.size()==0||sq.top().v>x) //如果后面的元素比栈顶小,则压入栈
sq.push(a);
else
{
while(sq.top().v<=x) //找比当前元素小的最前面的元素
{
ans=max(ans,i-sq.top().id);
//cout << "!!!!"<<sq.front().id << endl;
q.push(sq.top());
sq.pop();
if(sq.empty())
break;
}
while(!q.empty())
{
sq.push(q.top());
q.pop();
}
}
}
printf("%d\n",ans);
}
return 0;
}