一名苦逼的OIer,想成为ACMer

Iowa_Battleship

HDOJ2870 Largest Submatrix

一道\(DP\)

原题链接

发现只有\(a,b,c\)三种情况,所以直接初始化成三个\(01\)方阵,找最大子矩阵即可。
我是先初始化垂直上的高度,然后对每一行处理出每个点向左向右的最大延伸,并不断计算矩阵大小来更新答案。
因为不想开函数传数组,所以全写在主函数复制粘贴了三遍。。代码显得比较冗长。

#include<cstdio>
#include<cstring>
using namespace std;
const int N = 1010;
int A[N][N], B[N][N], C[N][N], l[N], r[N];
char re_l()
{
	char c = getchar();
	for (; c != 'a'&&c != 'b'&&c != 'c'&&c != 'x'&&c != 'y'&&c != 'z'&&c != 'w'; c = getchar());
	return c;
}
inline int maxn(int x, int y)
{
	return x > y ? x : y;
}
int main()
{
	int i, j, ma, n, m;
	char c;
	while (scanf("%d%d", &n, &m)==2)
	{
		ma = 1;
		memset(A, 0, sizeof(A));
		memset(B, 0, sizeof(B));
		memset(C, 0, sizeof(C));
		for (i = 1; i <= n; i++)
			for (j = 1; j <= m; j++)
			{
				c = re_l();
				if (c == 'a' || c == 'w' || c == 'y' || c == 'z')
					A[i][j] = A[i - 1][j] + 1;
				if (c == 'b' || c == 'w' || c == 'x' || c == 'z')
					B[i][j] = B[i - 1][j] + 1;
				if (c == 'c' || c == 'x' || c == 'y' || c == 'z')
					C[i][j] = C[i - 1][j] + 1;
			}
		for (i = 1; i <= n; i++)
		{
			for (j = 1; j <= m; j++)
				l[j] = r[j] = j;
			A[i][0] = A[i][m + 1] = -1;
			for (j = 1; j <= m; j++)
				while (A[i][j] <= A[i][l[j] - 1])
					l[j] = l[l[j] - 1];
			for (j = m; j; j--)
				while (A[i][j] <= A[i][r[j] + 1])
					r[j] = r[r[j] + 1];
			for (j = 1; j <= m; j++)
				ma = maxn(ma, (r[j] - l[j] + 1)*A[i][j]);
		}
		for (i = 1; i <= n; i++)
		{
			for (j = 1; j <= m; j++)
				l[j] = r[j] = j;
			B[i][0] = B[i][m + 1] = -1;
			for (j = 1; j <= m; j++)
				while (B[i][j] <= B[i][l[j] - 1])
					l[j] = l[l[j] - 1];
			for (j = m; j; j--)
				while (B[i][j] <= B[i][r[j] + 1])
					r[j] = r[r[j] + 1];
			for (j = 1; j <= m; j++)
				ma = maxn(ma, (r[j] - l[j] + 1)*B[i][j]);
		}
		for (i = 1; i <= n; i++)
		{
			for (j = 1; j <= m; j++)
				l[j] = r[j] = j;
			C[i][0] = C[i][m + 1] = -1;
			for (j = 1; j <= m; j++)
				while (C[i][j] <= C[i][l[j] - 1])
					l[j] = l[l[j] - 1];
			for (j = m; j; j--)
				while (C[i][j] <= C[i][r[j] + 1])
					r[j] = r[r[j] + 1];
			for (j = 1; j <= m; j++)
				ma = maxn(ma, (r[j] - l[j] + 1)*C[i][j]);
		}
		printf("%d\n", ma);
	}
	return 0;
}

posted on 2018-08-22 19:09  Iowa_Battleship  阅读(202)  评论(0编辑  收藏  举报

导航