# Imbalanced Array

## 题目描述

You are given an array $a$ consisting of $n$ elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.
For example, the imbalance value of array $[1, 4, 1]$ is $9$, because there are $6$ different subsegments of this array:

• $[1]$ (from index $1$ to index $1$), imbalance value is $0$;
• $[1, 4]$ (from index $1$ to index $2$), imbalance value is $3$;
• $[1, 4, 1]$ (from index $1$ to index $3$), imbalance value is $3$;
• $[4]$ (from index $2$ to index $2$), imbalance value is $0$;
• $[4, 1]$ (from index $2$ to index $3$), imbalance value is $3$;
• $[1]$ (from index $3$ to index $3$), imbalance value is $0$.

You have to determine the imbalance value of the array $a$.

## 题意概述

$$\sum_{1 \le i \le j \le n} (max_{i, j}-min_{i, j})$$

## 代码1

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
struct number {
long long num, id, rec;
} a[1000001];
bool cmp(number a, number b) {return a.num < b.num;}
long long n, fa[1000002], s[1000002], ans;
int get_fa(long long t) {
return t == fa[t] || fa[t] == 0 ? fa[t] : fa[t] = get_fa(fa[t]);
}
void process(int t) {
int i, j;
if (t == 1) i = 1, j = n + 1;
else i = n, j = 0;
for (; i != j; i += t) {
fa[a[i].id] = a[i].id;
s[a[i].id] = 1;
long long p = get_fa(a[i].id - 1), q = get_fa(a[i].id + 1);
a[i].rec = (s[p] + 1) * (s[q] + 1);
if (s[p]) {
s[p] += s[get_fa(a[i].id)];
fa[get_fa(a[i].id)] = p;
}
if (s[q]) {
s[q] += s[get_fa(a[i].id)];
fa[get_fa(a[i].id)] = q;
}
}
}
int main()
{
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i].num;
a[i].id = i;
}
sort(a + 1, a + n + 1, cmp);
process(1);
for (int i = 1; i <= n; ++i) {
ans += a[i].num * a[i].rec;
}
memset(fa, 0, sizeof(fa));
memset(s, 0, sizeof(s));
process(-1);
for (int i = 1; i <= n; ++i) {
ans -= a[i].num * a[i].rec;
}
cout << ans << endl;
return 0;
}


## 代码2

#include <iostream>
using namespace std;
long long n, a[1000001], l[1000001], r[1000001], ans;
void process(int t) {
for (int i = 1; i <= n; ++i) {
l[i] = r[i] = i;
}
for (int i = 2; i <= n; ++i) {
int now = i;
while (now > 1 && a[i] * t >= a[now - 1] * t) now = l[now - 1];
l[i] = now;
}
for (int i = n - 1; i; --i) {
int now = i;
while (now < n && a[i] * t > a[now + 1] * t) now = r[now + 1];
r[i] = now;
}
}
int main()
{
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
process(1);
for (int i = 1; i <= n; ++i) {
ans += a[i] * (i - l[i] + 1) * (r[i] - i + 1);
}
process(-1);
for (int i = 1; i <= n; ++i) {
ans -= a[i] * (i - l[i] + 1) * (r[i] - i + 1);
}
cout << ans << endl;
return 0;
}


418 I'm a teapot