POJ 2796 Feel Good (单调栈)

http://poj.org/problem?id=2796


和POJ 2559一样,把计算矩形的长改为前缀和就行。


完整代码:

/*891ms,2716KB*/

#include
#include
using namespace std;
const int mx = 100005;

__int64 h[mx], sum[mx];
int l[mx], r[mx];

int main()
{
	//freopen("in.txt", "r", stdin);
	int n, i, j, ansl, ansr;
	__int64 ans, tmp;
	scanf("%d", &n);
	for (i = 1; i <= n; ++i)
	{
		scanf("%I64d", &h[i]);
		sum[i] = sum[i - 1] + h[i];
	}
	for (i = 1; i <= n; ++i)
	{
		j = i;
		while (j > 1 && h[j - 1] >= h[i]) ///压栈否
			j = l[j - 1]; ///出栈
		l[i] = j;
	}
	for (i = n; i; --i)
	{
		j = i;
		while (j < n && h[j + 1] >= h[i]) ///压栈否
			j = r[j + 1]; ///出栈
		r[i] = j;
	}
	ans = -1;///注意数据中有0
	for (i = 1; i <= n; ++i)
	{
		tmp = h[i] * (sum[r[i]] - sum[(l[i] - 1)]);
		if (tmp > ans)
		{
			ans = tmp;
			ansl = l[i];
			ansr = r[i];
		}
	}
	printf("%I64d\n%d %d\n", ans, ansl, ansr);
	return 0;
}

你可能感兴趣的:(acm之路--数据结构,栈,POJ)