Range

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


#include <cstdio>
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;
#define M 100005
#define LL long long
int a[M],n;
int l[M],r[M];
int input()
{
    char c=getchar();
    int ret=0;
    while(c<'0'||c>'9')c=getchar();
    while(c>='0'&&c<='9')
    {
        ret=ret*10+c-'0';
        c=getchar();
    }
    return ret;
}
LL solve()
{
    stack<int> s;
    LL ans=0;
    while(!s.empty())s.pop();
    //l[i]记录左边比a[i]小的数
    s.push(-1);
    for(int i=0;i<n;i++)
    {
        while(s.top()!=-1&&a[s.top()]<a[i])
            s.pop();
        l[i]=s.top()+1;
        s.push(i);
    }
    while(!s.empty())s.pop();
    //r[i] 记录右边比a[i]小或等的数
     s.push(n);
    for(int i=n-1;i>=0;i--)
    {
        while(s.top()!=n&&a[s.top()]<=a[i])
            s.pop();
        r[i]=s.top()-1;
        s.push(i);
    }
    for(int i=0;i<n;i++)
        ans+=(LL)a[i]*(i-l[i]+1)*(r[i]-i+1);
    /**----------------------------------------------*/

    while(!s.empty())s.pop();
    //l[i]记录左边比a[i]大的数
    s.push(-1);
    for(int i=0;i<n;i++)
    {
        while(s.top()!=-1&&a[s.top()]>a[i])
            s.pop();
        l[i]=s.top()+1;
        s.push(i);
    }
    while(!s.empty())s.pop();
    //r[i] 记录右边比a[i]大或等的数
     s.push(n);
    for(int i=n-1;i>=0;i--)
    {
        while(s.top()!=n&&a[s.top()]>=a[i])
            s.pop();
        r[i]=s.top()-1;
        s.push(i);
    }
    for(int i=0;i<n;i++)
        ans-=(LL)a[i]*(i-l[i]+1)*(r[i]-i+1);
   // Cn2,+n
    return ans+(LL)n*(n+1)/2;
}
int main()
{
    int T;
    scanf("%d",&T);
    for(int i=1;i<=T;i++)
    {
       scanf("%d",&n);
       for(int j=0;j<n;j++)
         a[j]=input();

       LL ans=solve();
       cout<<"Case "<<i<<": "<<ans<<endl;
    }

    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值