Codeforces Round #333 (Div. 1)--B. Lipshitz Sequence 单调栈
2015-11-29 01:42
459 查看
题意:n个点, 坐标已知,其中横坐标为为1~n。 求区间[l, r] 的所有子区间内斜率最大值的和。
首先要知道,[l, r]区间内最大的斜率必然是相邻的两个点构成的。
然后问题就变成了求区间[l, r]内所有子区间最大值的和。
这个问题可以利用单调栈来做。
每次找到当前点左面第一个大于当前值的点, 然后更新答案。 姿势很多。
首先要知道,[l, r]区间内最大的斜率必然是相邻的两个点构成的。
然后问题就变成了求区间[l, r]内所有子区间最大值的和。
这个问题可以利用单调栈来做。
每次找到当前点左面第一个大于当前值的点, 然后更新答案。 姿势很多。
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.Scanner; public class Main { static Scanner cin = new Scanner(new BufferedInputStream(System.in)); static PrintWriter cout = new PrintWriter(new BufferedOutputStream(System.out)); static final int maxn = 100005; public static void main(String[] args) { int []height = new int[maxn]; while (cin.hasNext()){ int n = cin.nextInt(); int q = cin.nextInt(); height[0] = 0; for (int i = 1; i <= n; i++){ height[i] = cin.nextInt(); height[i-1] = Math.abs(height[i]-height[i-1]); } int []stack = new int[maxn]; int top = -1; for (int i = 0; i < q; i++){ int l = cin.nextInt(); int r = cin.nextInt(); long res = 0, cur = 0; top = -1; for (int j = l; j < r; j++){ while (top >= 0 && height[stack[top]] <= height[j]){ cur -= 1L * height[stack[top]] * (stack[top] - (top==0 ? l-1 : stack[top-1])); top--; } if (top >= 0){ cur += 1L* (j - stack[top]) * height[j]; }else{ cur += 1L * (j - l + 1) * height[j]; } stack[++top] = j; res += cur; } cout.println(res); } cout.flush(); } } }
相关文章推荐
- 【UI进阶】关于IB的理解,不知道这样是否可以
- 1017. Queueing at Bank (25)——PAT (Advanced Level) Practise
- 【UI进阶】IB(Interface Builder)的一点小总结
- AJ学IOS 之UIDynamic重力、弹性碰撞吸附等现象
- AJ学IOS 之微博项目实战(7)程序启动新特性用UICollectionViewController实现
- AJ学IOS 之微博项目实战(3)微博主框架-UIImage防止iOS7之后自动渲染_定义分类
- AJ学IOS(42)UI之核心动画CAAnimationGroup以及其他
- AJ学IOS(41)UI之核心动画 两行代码搞定3D转场
- AJ学IOS(40)UI之核心动画_抖动效果_CAKeyframeAnimation
- AJ学IOS(39)UI之核心动画之CABasicAnimation(基础动画)
- AJ学IOS(38)UI之核心动画简介
- AJ学IOS(37)UI之CALayer
- AJ学IOS(36)UI之手势事件旋转_缩放_拖拽
- AJ学IOS(35)UI之Quartz2D仿真支付宝手势解锁_代理获得密码。
- AJ学IOS(34)UI之Quartz2D画画板的实现
- AJ学IOS(33)UI之Quartz2D雪花飘落效果刷帧
- AJ学IOS(32)UI之Quartz2D矩阵操作和图片剪切
- AJ学IOS(31)UI之Quartz2D图形上下文栈
- AJ学IOS(30)UI之Quartz2D画图片画文字
- AJ学IOS(29)UI之Quartz2D自定义下载控件_画各种图形