单调栈求最大矩形面积(洛谷4147)

#include
using namespace std;
int n, m, pos[1005][1005];
int ans, maxs;
char x;
struct node
{
	int height, length;
}s[1005];
void calc(int x)
{
	int top = 1, temp = 0;
	maxs = 0;
	s[1].height = pos[x][1];
	s[1].length = 1;
	for (int i = 2; i <= m; i++)
	{
		temp = 0;
		while (s[top].height > pos[x][i] && top > 0)
		{
			temp += s[top].length;
			maxs = max(maxs, s[top--].height*temp);
		}
		s[++top].height = pos[x][i];
		s[top].length = temp + 1;
	}
	temp = 0;
	while (top)
	{
		temp += s[top].length;
		maxs = max(maxs, s[top--].height*temp);
	}
	ans = max(ans, maxs);
}
int main()
{
	while (cin >> n >> m)
	{
		ans = 0;
		memset(pos, 0, sizeof(pos));
		for(int i=1;i<=n;i++)
			for (int j = 1; j <= m; j++)
			{
				cin >> x;
				if (x == 'F')pos[i][j] = pos[i - 1][j] + 1;
			}
		for (int i = 1; i <= n; i++)calc(i);
		cout << ans * 3 << endl;
	}
	return 0;
}

枚举每一行,用单调栈维护每一列能向上延伸的最大长度,每次出栈时更新结果

你可能感兴趣的:(算法)