Codeforces 817D Imbalanced Array

来源:互联网 发布:vue.js事件对象event 编辑:程序博客网 时间:2024/06/06 09:08

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. Theimbalance value of the array is the sum ofimbalance values of all subsegments of this array.

For example, the imbalance value of array[1, 4, 1] is 9, because there are6 different subsegments of this array:

  • [1] (from index 1 to index1), imbalance value is0;
  • [1, 4] (from index 1 to index2), imbalance value is3;
  • [1, 4, 1] (from index 1 to index3), imbalance value is3;
  • [4] (from index 2 to index2), imbalance value is0;
  • [4, 1] (from index 2 to index3), imbalance value is3;
  • [1] (from index 3 to index3), imbalance value is0;

You have to determine the imbalance value of the arraya.

Input

The first line contains one integer n (1 ≤ n ≤ 106) — size of the arraya.

The second line contains n integers a1, a2...an (1 ≤ ai ≤ 106) — elements of the array.

Output

Print one integer — the imbalance value ofa.

Example
Input
31 4 1
Output
9
这个题,想了挺长时间的,就是不出啊,脑袋都想爆炸了,最后还是看的别人的代码,我就是水个积分,希望他不会怪罪啦(都是一个学校的,希望不要打我啊)如果想看最最最牛逼的代码与讲解请点击这里,想听我讲的也可以继续。。。。。
题目大意:计算所有子区间里最大值和最小值差的和
题解:我们可以分开来计算,计算每一个位置能做最大值的次数和能做最小值的次数,然后用做最大值得到的价值的和减去做最小值得到的价值的和,就是这个位置所做的贡献,然后求下和就好啦。
AC代码
#include<bits/stdc++.h>#define int long longusing 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);}

原创粉丝点击