51nod 1272 最大距離 (單調棧)
阿新 • • 發佈:2019-01-22
1272 最大距離
基準時間限制: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
Output
第1行:1個數N,表示陣列的長度(2 <= N <= 50000)。 第2 - N + 1行:每行1個數,對應陣列元素Ai(1 <= Ai <= 10^9)。
輸出最大距離。Input示例
6 5 3 6 3 4 2Output示例
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); } }