本文主要是介绍CodeForces 817D : Imbalanced Array 单调栈,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
传送门
题意
对于给定由 n 个元素构成的数组。一个子数组的不平衡值是这个区间的最大值与最小值的差值。数组的不平衡值是它所有子数组的不平衡值的总和。求数组的不平衡值。
分析
我们用单调栈处理出来每一个数可以作为最大值位于哪个区间,作为最小值位于哪个区间,然后计算一下贡献即可
需要注意的是,因为可能会有区间数字重复的问题,所以在处理单调栈的时候,可以一半取等,一半不取等
代码
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 2e6 + 10;
const ll mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a) {char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) {if (c == '-')f = -1; c = getchar();}while (isdigit(c)) {x = (x << 1) + (x << 3) + c - '0'; c = getchar();} a = f * x;
}
int gcd(int a, int b) {return (b > 0) ? gcd(b, a % b) : a;}
int l1[N], r1[N]; //最大的区间
int l2[N], r2[N]; // 最小的区间
int s1[N], s2[N];
int t1, t2;
int a[N];
int n;int main() {read(n);for (int i = 1; i <= n; i++) read(a[i]);t1 = 0, t2 = 0;s1[t1] = s2[t2] = 0;for (int i = 1; i <= n; i++) {while (t1 && a[s1[t1]] <= a[i]) t1--;l1[i] = s1[t1] + 1;while (t2 && a[s2[t2]] >= a[i]) t2--;l2[i] = s2[t2] + 1;s1[++t1] = i;s2[++t2] = i;}t1 = 0, t2 = 0;s1[t1] = s2[t2] = n + 1;for (int i = n; i; i--) {while (t1 && a[s1[t1]] < a[i]) t1--;r1[i] = s1[t1] - 1;while (t2 && a[s2[t2]] > a[i]) t2--;r2[i] = s2[t2] - 1;s1[++t1] = i;s2[++t2] = i;}ll res = 0;for (int i = 1; i <= n; i++) {ll t = 1ll * (i - l1[i] + 1) * (r1[i] - i + 1) - 1ll * (i - l2[i] + 1) * (r2[i] - i + 1);res += 1ll * a[i] * t;}dl(res);return 0;
}
这篇关于CodeForces 817D : Imbalanced Array 单调栈的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!