51nod1272最大距离

题目描述

给出一个长度为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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值