您的位置:首页 > 产品设计 > UI/UE

Codeforces Round #333 (Div. 1)--B. Lipshitz Sequence 单调栈

2015-11-29 01:42 459 查看
题意:n个点, 坐标已知,其中横坐标为为1~n。 求区间[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();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: