首页 > 代码库 > URAL 1287. Mars Canals 滚动数组+DP

URAL 1287. Mars Canals 滚动数组+DP

求从上到下 从左到右 从左上到右下 从右上到左下的 最长的S和s串

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1444;
char a[maxn][maxn];
int dp[2][maxn][2][4];
int main()
{
	int n;
	int ans1 = 0, ans2 = 0;
	scanf("%d", &n);
	for(int i = 1; i <= n; i++)
		scanf("%s", a[i]+1);
	int l = 1, r = l^1;
	for(int i = 1; i <= n; i++)
	{
		l = r;
		r = l^1;
		for(int j = 1; j <= n; j++)
		{
			if(i > 1 && a[i][j] == a[i-1][j])
			{
				if(a[i][j] == 'S')
					dp[l][j][0][0] = dp[r][j][0][0]+1;
				else
					dp[l][j][1][0] = dp[r][j][1][0]+1;
			}
			else
			{
				if(a[i][j] == 'S')
					dp[l][j][0][0] = 1;
				else
					dp[l][j][1][0] = 1;
			}
			if(j > 1 && a[i][j] == a[i][j-1])
			{
				if(a[i][j] == 'S')
					dp[l][j][0][1] = dp[l][j-1][0][1]+1;
				else
					dp[l][j][1][1] = dp[l][j-1][1][1]+1;
			}
			else
			{
				if(a[i][j] == 'S')
					dp[l][j][0][1] = 1;
				else
					dp[l][j][1][1] = 1;
			}
			if(i > 1 && j > 1 && a[i][j] == a[i-1][j-1])
			{
				if(a[i][j] == 'S')
					dp[l][j][0][2] = dp[r][j-1][0][2]+1;
				else
					dp[l][j][1][2] = dp[r][j-1][1][2]+1;
			}
			else
			{
				if(a[i][j] == 'S')
					dp[l][j][0][2] = 1;
				else
					dp[l][j][1][2] = 1;
			}
			if(i > 1 && j < n && a[i][j] == a[i-1][j+1])
			{
				if(a[i][j] == 'S')
					dp[l][j][0][3] = dp[r][j+1][0][3]+1;
				else
					dp[l][j][1][3] = dp[r][j+1][1][3]+1;
			}
			else
			{
				if(a[i][j] == 'S')
					dp[l][j][0][3] = 1;
				else
					dp[l][j][1][3] = 1;
			}
			
			ans1 = max(max(ans1, dp[l][j][0][0]), max(dp[l][j][0][1], dp[l][j][0][2]));
			ans1 = max(ans1, dp[l][j][0][3]);
			ans2 = max(max(ans2, dp[l][j][1][0]), max(dp[l][j][1][1], dp[l][j][1][2])); 
			ans2 = max(ans2, dp[l][j][1][3]);
			//printf("%d %d\n", ans1, ans2);
		}
	}
	if(ans1 > ans2)
		printf("%c %d\n", 'S', ans1);
	else if(ans1 < ans2)
		printf("%c %d\n", 's', ans2);
	else
		printf("%c %d\n", '?', ans1);
	return 0;
}


URAL 1287. Mars Canals 滚动数组+DP