51nod 1272 最大距离 (单调栈)

1272 最大距离
题目来源: Codility
基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题
收藏
关注
给出一个长度为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。
Input
第1行:1个数N,表示数组的长度(2 <= N <= 50000)。
第2 - N + 1行:每行1个数,对应数组元素Ai(1 <= Ai <= 10^9)。
Output
输出最大距离。
Input示例
6
5
3
6
3
4
2
Output示例
3


思路:用一个单调递减的栈来保存元素。


#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <functional>
#include <cmath>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <stack>
using namespace std;
#define esp  1e-8
const double PI = acos(-1.0);
const double e = 2.718281828459;
const int inf = 2147483647;
const long long mod = 1000000007;
//freopen("in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取
//freopen("out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中cin

struct node
{
	int id, v;
};
stack<node>sq, q;
int main()
{
	int n, i, j;
	while (~scanf("%d", &n))
	{
		while (!sq.empty())
		{
			sq.pop();
		}
		int x;
		int ans = 0;
		for (i = 1; i <= n; ++i)
		{
			scanf("%d", &x);
			node a;
			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);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值