题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1506
单调栈STL写法。
维护一个单调递增的单调栈,栈中元素为二元组(h,pos),h为第一关键字。弹出栈时更新最大值。
代码:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#define ll long long
#define ull unsigned long long
#define BUG cout<<"*************************"<<endl
using namespace std;
const ll mod = 998244353;
const int maxn = 1e5 + 10;
const int maxm = 1e6 + 10000;
const double eps = 1e-8;
stack<pair<ll, ll> > s;
ll n, a[maxn];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
while (cin >> n) {
if (n == 0)break;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
ll ans = 0;
for (ll i = 1; i <= n; ++i) {
while (!s.empty() && s.top().first > a[i]) {
pair<ll, ll> p = s.top();
s.pop();
if (s.empty()) {
ans = max(ans, p.first * (i - 1));
}
else {
ans = max(ans, (i - 1 - s.top().second) * p.first);
}
}
s.push(pair<int, int>(a[i], i));
}
while (!s.empty()) {
pair<ll, ll> p = s.top();
s.pop();
if (s.empty()) {
ans = max(ans, n * p.first);
}
else {
ans = max(ans, (n - s.top().second) * p.first);
}
}
cout << ans << endl;
}
return 0;
}