POJ2796 区间最大参考值
2012-11-27 21:19
399 查看
给定一个数组,定义某个区间的参考值为:区间所有元素的和*区间最小元素。求该数组中的最大参考值以及对应的区间。
设某个区间所有元素的和为height,区间最小元素为width,
则对于单个元素的区间,height = width = 元素的值。
建立一个单调递增的栈。从第一个元素开始入栈,每个元素入栈之前必须先从栈顶开始删除大于或等于它的元素,把删除的所有元素的height累加到当前元素的height,然后把当前元素的值保存在width值中,这表示把当前元素前面比它大或相等的连续元素的值加起来,乘以它自己,也就是这段区间的参考值。每一次删除元素都需要计算一个参考值,取参考值的最大值就是答案了。不过题目还要求给出对应区间的起点和终点,因此在栈的操作过程中还得记录当前元素保存的区间的起点和大小,在更新参考值的过程中顺便更新区间的起点和终点就可以了。
设某个区间所有元素的和为height,区间最小元素为width,
则对于单个元素的区间,height = width = 元素的值。
建立一个单调递增的栈。从第一个元素开始入栈,每个元素入栈之前必须先从栈顶开始删除大于或等于它的元素,把删除的所有元素的height累加到当前元素的height,然后把当前元素的值保存在width值中,这表示把当前元素前面比它大或相等的连续元素的值加起来,乘以它自己,也就是这段区间的参考值。每一次删除元素都需要计算一个参考值,取参考值的最大值就是答案了。不过题目还要求给出对应区间的起点和终点,因此在栈的操作过程中还得记录当前元素保存的区间的起点和大小,在更新参考值的过程中顺便更新区间的起点和终点就可以了。
#include <iostream> #include <cstdio> using namespace std; const int N = 100005; struct Elem { long long height; long long width; int begin; int count; }; Elem stack ; int top; int main() { int num, n; long long ans, tmp, tot; int ansbeg, ansend, count; scanf("%d", &n); top = 0; ans = 0; ansbeg = ansend = 1; for (int i = 0; i < n; ++i) { scanf("%d", &num); tmp = 0; count = 0; while (top > 0 && stack[top - 1].width >= num) { stack[top - 1].count += count; tot = (stack[top - 1].height + tmp) * stack[top - 1].width; if (tot > ans) { ans = tot; ansbeg = stack[top - 1].begin; ansend = ansbeg + stack[top - 1].count - 1; } tmp += stack[top - 1].height; count = stack[top - 1].count; --top; } stack[top].height = num + tmp; stack[top].width = num; stack[top].begin = i + 1 - count; stack[top].count = 1 + count; ++top; } tmp = 0; count = 0; while (top > 0) { stack[top - 1].count += count; tot = (stack[top - 1].height + tmp) * stack[top - 1].width; if (tot > ans) { ans = tot; ansbeg = stack[top - 1].begin; ansend = ansbeg + stack[top - 1].count - 1; } tmp += stack[top - 1].height; count = stack[top - 1].count; --top; } printf("%lld\n%d %d\n", ans, ansbeg, ansend); return 0; }
相关文章推荐
- POJ 2796 Feel Good (单调栈 区间最大值)
- POJ 2796 Feel Good (单调栈 区间最大值)
- POJ 2796 Feel Good (单调栈 区间最大值)
- POJ 2796 Feel Good (单调栈 区间最大值)
- POJ 2796 Feel Good (单调栈 区间最大值)
- poj 递增栈 POJ2796 区间最大参考值 3250牛的视野
- POJ 2796 Feel Good (单调栈 区间最大值)
- POJ 2796 Feel Good (单调栈 区间最大值)
- POJ 2796 Feel Good (单调栈 区间最大值)
- POJ 2689 Prime Distance(区间相邻素数最大、小距离,区间素数筛)
- POJ - 3762 The Bonus Salary! 区间图的最大权独立集(最大流)
- POJ 题目2823 Sliding Window(单调队列求定长区间最大值)
- POJ 3264 Balanced Lineup 区间查询(两棵树求最大最小值)
- 【POJ 2955】【经典区间DP 递推写法】 Brackets 【合法括号匹配成功结果+2,求最大结果】
- POJ 2955 Brackets 区间DP 最大括号匹配
- POJ 3264 Balanced Lineup 区间查询(两棵树求最大最小值)
- poj2750-Potted Flower-动态求最大连续环区间和(线段树上分治+set维护)
- POJ 3616 Milking Time(DP,区间和最大)
- POJ 3264 Balanced Lineup 区间查询(两棵树求最大最小值)
- POJ 题目2750 Potted Flower(线段树求环型区间中连续区间的最大和)