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;
}