Range

来源:互联网 发布:局域网视频聊天软件 编辑:程序博客网 时间:2024/05/16 18:19

Range

Accepted : 81 Submit : 467Time 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

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

0 0
原创粉丝点击