第1行:1個數N,表示數組的長度(0 <= N <= 50000)第2 - N + 1行:數組元素A[i]。(1 <= A[i] <= 10^9)Output輸出最大的矩形面積Input示例6215623Output示例10思路:
單調棧的模板題,枚舉最低點,然后找到左右的邊界。代碼:
#include <bits/stdc++.h>using namespace std;typedef long long ll;const int MAXN = 5e4 + 10;ll a[MAXN];int l[MAXN], r[MAXN];int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%I64d", &a[i]); stack <int> sta; for (int i = 1; i <= n; i++) { while (!sta.empty() && a[sta.top()] >= a[i]) sta.pop(); l[i] = sta.empty() ? 0 : sta.top(); sta.push(i); } while (!sta.empty()) sta.pop(); for (int i = n; i >= 1; i--) { while (!sta.empty() && a[sta.top()] >= a[i]) sta.pop(); r[i] = sta.empty() ? n + 1 : sta.top(); sta.push(i); } ll ans = 0; for (int i = 1; i <= n; i++) ans = max(ans, (r[i] - l[i] - 1) * a[i]); PRintf("%I64d/n", ans); return 0;}
新聞熱點
疑難解答