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.
InputThe 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
这个题,想了挺长时间的,就是不出啊,脑袋都想爆炸了,最后还是看的别人的代码,我就是水个积分,希望他不会怪罪啦(都是一个学校的,希望不要打我啊)如果想看最最最牛逼的代码与讲解请点击这里,想听我讲的也可以继续。。。。。
题目大意:计算所有子区间里最大值和最小值差的和
题解:我们可以分开来计算,计算每一个位置能做最大值的次数和能做最小值的次数,然后用做最大值得到的价值的和减去做最小值得到的价值的和,就是这个位置所做的贡献,然后求下和就好啦。
AC代码#include<bits/stdc++.h> #define int long long using namespace std; const int N = 1e6 + 7; int a[N]; int l[N]; int r[N]; int32_t main() { int ans = 0, n, i; for(i = 1, scanf("%I64d", &n); i <= n; scanf("%I64d", &a[i++])); for(i = 1; i <= n; l[i] = r[i] = i, i++); for(i = 2; i <= n; i++) { int num = i; while(num > 1 && a[num - 1] <= a[i]) num = l[num - 1]; l[i] = num; } for(i = n - 1; i >= 1; i--){ int num = i; while(num < n && a[num + 1] < a[i]) num = r[num + 1]; r[i] = num; } for(i = 1; i <= n; ans += (i - l[i] + 1)*(r[i] - i + 1)* a[i], i++); for(i = 1; i <= n; l[i] = r[i] = i, i++); for(i = 2; i <= n; i++){ int num = i; while(num > 1 && a[num - 1] >= a[i]) num = l[num - 1]; l[i] = num; } for(i = n - 1; i >= 1; i--){ int num = i; while(num < n && a[num + 1] > a[i]) num = r[num + 1]; r[i] = num; } for(i = 1; i <= n; i++){ ans -= (i - l[i] + 1)*(r[i] - i + 1) * a[i]; } printf("%I64d\n", ans); }