Range
来源:互联网 发布:局域网视频聊天软件 编辑:程序博客网 时间:2024/05/16 18:19
Range
Accepted : 81 Submit : 467Time Limit : 1000 MS Memory Limit : 65536 KBProblem 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
- Range
- Range
- range
- range()
- Range
- range
- Range
- Range
- Range
- range
- range
- range和content-range
- time-range
- python--range()
- HTTP Range
- Range Name
- USACO--range
- Dynamic Range
- 完整的FreeBSD软件安装方法
- Java加密技术(一)单向加密算法MD5&SHA&MAC与BASE64
- java之合并链表的两种方法
- C语言字符数组的初始化
- iOS开发系列--UITableView全面解析
- Range
- 扫描密码文件和组文件中的所有记录。
- 长度小于8000(varchar类型),以"逗号"分隔的字符串
- C# List<T>用法
- Oracle WebLogic Server 11g 集群部署On Linux
- 在SQL中参数值超过8000(TEXT类型)的处理方法,以"逗号"分隔的字符串
- linux下安装Apache+php+mysql
- leetcode 之 Length of Last Word
- 长沙市护照港澳通行证办理