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

来源:互联网 发布:个人网站域名名字 编辑:程序博客网 时间:2024/05/22 08:19
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示例
6536342
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-8const 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文件中cinstruct 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
原创粉丝点击