Codeforces 817D 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.

Input

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.

Output

Print one integer — the imbalance value of a.

Example
Input
3
1 4 1
Output
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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值