POJ2559 Largest Rectangle in a Histogram

传送


单调栈经典题,以前总写不对,有些心里阴影,故在此放一个代码。


其主要思路就是保持栈一直单调递增,然后只有在被弹栈的时候才统计以这个竖块为左边界的矩形的面积。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<queue>
#include<assert.h>
#include<ctime>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
#define forE(i, x, y) for(int i = head[x], y; ~i && (y = e[i].to); i = e[i].nxt)
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 1e5 + 5;
In ll read()
{
	ll ans = 0;
	char ch = getchar(), las = ' ';
	while(!isdigit(ch)) las = ch, ch = getchar();
	while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
	if(las == '-') ans = -ans;
	return ans;
}
In void write(ll x)
{
	if(x < 0) x = -x, putchar('-');
	if(x >= 10) write(x / 10);
	putchar(x % 10 + '0');
}
In void MYFILE()
{
#ifndef mrclr
	freopen(".in", "r", stdin);
	freopen(".out", "w", stdout);
#endif
}

int n;
struct Node
{
	int h, w;
}st[maxn];
int top = 0;
ll ans = 0;

In void Push(int h)
{
	if(!top || h > st[top].h) st[++top] = (Node){h, 1};
	else
	{
		int tp = 0;
		while(top && st[top].h >= h)
		{
			ans = max(ans, 1LL * st[top].h * (st[top].w + tp));
			tp += st[top--].w;
		}
		st[++top] = (Node){h, tp + 1};
	}
}

int main()
{
//	MYFILE();
	while(scanf("%d", &n) && n)
	{
		ans = top = 0;
		for(int i = 1; i <= n; ++i) Push(read());
		Push(0);
		write(ans), enter;
	}
	return 0;
}
posted @ 2021-07-21 17:53  mrclr  阅读(27)  评论(0编辑  收藏  举报