2014湘潭邀请赛 C题 湘大OJ 1205 Range (单调栈)
来源:互联网 发布:淘宝无线优惠券链接 编辑:程序博客网 时间:2024/05/22 05:30
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
实际上就是求出以第i个数为最大值得区间个数 和 以第i个数为最小值得区间个数 ,可以利用单调栈的思想,和poj2559几乎是一个题。都是求出以第i个为最值,往左往右能扩展出的范围。
#include <iostream>#include <cstdio>using namespace std;typedef __int64 LL;const int maxn = 100000+10;int t, n;LL l[maxn], r[maxn], a[maxn];LL solve(){ LL ans = (LL)(n+1)*n/2; l[1] = 1; for(int i = 2; i <= n; i++) { int tmp = i; while(tmp > 1 && a[tmp-1] >= a[i]) tmp = l[tmp-1]; l[i] = tmp; } r[n] = n; for(int i = n-1; i > 0; i--) { int tmp = i; while(tmp < n && a[tmp+1] > a[i]) tmp = r[tmp+1]; r[i] = tmp; } for(int i = 1; i <= n; i++) ans -= a[i] * (LL)(i - l[i] + 1) * (LL)(r[i] - i + 1); l[1] = 1; for(int i = 2; i <= n; i++) { int tmp = i; while(tmp > 1 && a[tmp-1] <= a[i]) tmp = l[tmp-1]; l[i] = tmp; } r[n] = n; for(int i = n-1; i > 0; i--) { int tmp = i; while(tmp < n && a[tmp+1] < a[i]) tmp = r[tmp+1]; r[i] = tmp; } for(int i = 1; i <= n; i++) ans += a[i] * (LL)(i - l[i] + 1) * (LL)(r[i] - i + 1); return ans;}int main(){ cin >> t; for(int ca = 1; ca <= t; ca++) { cin >> n; for(int i = 1; i < n+1; i++) scanf("%I64d", &a[i]); printf("Case %d: %I64d\n", ca, solve()); } return 0;}
2 0
- 2014湘潭邀请赛 C题 湘大OJ 1205 Range (单调栈)
- XTU 1205 Range 2014湖南邀请赛C 单调栈
- 2016 湘潭邀请赛 c 题 Hamiltonian Path
- XTU 1203 A simple problem (2014 湖南湘潭邀请赛 A题)(数学)
- 15年湘潭邀请赛 D题 Fraction
- 15年湘潭邀请赛 A题 Coins
- 湘潭邀请赛 A题 矩阵快速幂
- 2017 湘潭大学邀请赛H题--Highway
- 湘潭邀请赛G- Parentheses(贪心,思维)
- Echo (湘潭大学OJ)
- Partial Sum(湘潭邀请赛E题(部分和问题))
- ACM_ICPC 湘潭邀请赛
- 湘潭邀请赛总结
- 湘潭邀请赛A
- 2015湘潭邀请赛小记
- 2015 湘潭邀请赛 Fraction
- 2015 湘潭邀请赛 Tuples
- 2015湘潭邀请赛 CQRXLB
- Android入门环境搭建
- Oracle webcenter装配配置使用
- NTP - UDP 123
- C#文件流操作
- js中几种方法的使用总结
- 2014湘潭邀请赛 C题 湘大OJ 1205 Range (单调栈)
- Gvim常用操作
- [leetcode] Anagrams
- 黑马程序员----反射
- 阿里校招笔试
- Android学习及如何利用android来赚钱
- NYOJ-素数
- C++ primer 第五版 中文版 练习 10.1 个人code
- 4646464646464464564