1.题目描述:
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.
The first line contains one integer n (1 ≤ n ≤ 106) — size of the array a.
The second line contains n integers a1, a2... an (1 ≤ ai ≤ 106) — elements of the array.
Print one integer — the imbalance value of a.
3 1 4 1
9
给你n个数a[1..n]定义连续子段imbalance值为最大值和最小值的差,要你求这个数组的imbalance总值
3.解题思路:
考虑每个位置作为最值向两边的最大拓展,最小值取负号,最大值取正号,求和即可。怎么去找呢?可以维护一个单调递增栈、单调递减栈,类似于POJ-2559
4.AC代码:
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define maxn 1000010
#define lson root << 1
#define rson root << 1 | 1
#define lent (t[root].r - t[root].l + 1)
#define lenl (t[lson].r - t[lson].l + 1)
#define lenr (t[rson].r - t[rson].l + 1)
#define N 1111
#define eps 1e-6
#define pi acos(-1.0)
#define e exp(1.0)
using namespace std;
const int mod = 1e9 + 7;
typedef long long ll;
typedef unsigned long long ull;
int a[maxn];
int l_min[maxn], r_min[maxn], l_max[maxn], r_max[maxn];
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
long _begin_time = clock();
#endif
int n;
while (~scanf("%d", &n))
{
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
l_min[1] = l_max[1] = 0;
for (int i = 2; i <= n; i++)
{
l_min[i] = l_max[i] = i - 1;
while (l_min[i] >= 1 && a[l_min[i]] > a[i])
l_min[i] = l_min[l_min[i]];
while (l_max[i] >= 1 && a[l_max[i]] < a[i])
l_max[i] = l_max[l_max[i]];
}
r_min[n] = r_max[n] = n + 1;
for (int i = n - 1; i > 0; i--)
{
r_min[i] = r_max[i] = i + 1;
while (r_min[i] <= n && a[r_min[i]] >= a[i])
r_min[i] = r_min[r_min[i]];
while (r_max[i] <= n && a[r_max[i]] <= a[i])
r_max[i] = r_max[r_max[i]];
}
ll ans = 0;
for (int i = 1; i <= n; i++)
{
ans -= 1LL * (i - l_min[i]) * (r_min[i] - i) * a[i];
ans += 1LL * (i - l_max[i]) * (r_max[i] - i) * a[i];
}
printf("%I64d\n", ans);
}
#ifndef ONLINE_JUDGE
long _end_time = clock();
printf("time = %ld ms.", _end_time - _begin_time);
#endif
return 0;
}