Range

Range

Accepted : 81 Submit : 467
Time Limit : 1000 MS Memory Limit : 65536 KB

Problem Description

For an array, the range function is defined below: Range(A)=Max(A)-Min(A)+1; For example, suppose A={1,2,3,4,5}, then Range(A)=5-1+1=5. Now, given an array A(length≤100000), you are going to calcalute the sum of all subarray's range. i.e sigma(i,j){Range(A[i,j])}.

Input

First line contain an integer T, there are T(1≤T≤100) cases. For each case T. The length N(1≤N≤100000), and N integers A[i](1≤A[i]≤109).

Output

Output case number first, then the answer.

Sample Input
1
5
1 2 3 4 5


Sample Output
Case 1: 35


Source

daizhenyang 
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<iostream>
#include<set>
#include<map>
#include<list>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
#define maxn 100000+20
#define LL long long
int a[maxn];
int st[maxn];
int maxL[maxn], maxR[maxn], minL[maxn], minR[maxn];
int main()
{
    int T, cnt = 0;
    scanf("%d", &T);
    while (T--)
    {
        int n;
        scanf("%d", &n);
        for (int i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        //  求作为最小值   所在的区间   单调递增进栈  左闭右闭
        int t = 1;
        for (int i = 1; i <= n; i++){
            while (t>1 && a[st[t - 1]] > a[i])t--;
            minL[i] = t == 1 ? 1 : (st[t - 1] + 1);
            st[t++] = i;
        }
        t = 1;
        for (int i = n; i >= 1; i--){
            while (t>1 && a[st[t - 1]] >= a[i])t--;
            minR[i] = t == 1 ? n : (st[t - 1] - 1);
            st[t++] = i;
        }
        //  求作为最小值   所在的区间   单调递增进栈  左闭右闭
        t = 1;
        for (int i = 1; i <= n; i++){
            while (t>1 && a[st[t - 1]] < a[i])t--;
            maxL[i] = t == 1 ? 1 : (st[t - 1] + 1);
            st[t++] = i;
        }
        t = 1;
        for (int i = n; i >= 1; i--){
            while (t>1 && a[st[t - 1]] <= a[i])t--;
            maxR[i] = t == 1 ? n : (st[t - 1] - 1);
            st[t++] = i;
        }
        LL ans = 0;
        for (int i = 1; i <= n; i++){
            ans += (LL)((LL)(i - maxL[i])*(maxR[i] - i) + maxR[i] - maxL[i])*a[i];
            ans -= (LL)((LL)(i - minL[i])*(minR[i] - i) + minR[i] - minL[i])*a[i];
        }
        ans += (LL)n*(n + 1) / 2;
        cnt += 1;
        cout << "Case " << cnt << ": " << ans << endl;
    }
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值