429B


  Posted on 11 Dec 2014
dynamic programming

Solution


#include <cstdio>
#include <algorithm>
using namespace std;

const int MAX_M = 1010;
const int MAX_N = 1010;

int n, m;
int gain[MAX_N][MAX_M];
int up_right[MAX_N][MAX_M];
int up_left[MAX_N][MAX_M];
int down_left[MAX_N][MAX_M];
int down_right[MAX_N][MAX_M];


void work(int f[][MAX_M], int s1, int e1, int d1, int s2, int e2, int d2)
{
	for (int i = s1; i != e1 + d1; i += d1)
		for (int j = s2; j != e2 + d2; j += d2)
			f[i][j] = gain[i][j] + max(f[i - d1][j], f[i][j - d2]);
}

int main()
{
	//input
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			scanf("%d", &gain[i][j]);
	//work
	work(down_right, 1, n, 1, 1, m, 1);
	work(up_right, n, 1, -1, 1, m, 1);
	work(down_left, 1, n, 1, m, 1, -1);
	work(up_left, n, 1, -1, m, 1, -1);
	int ans = 0;
	for (int i = 2; i <= n - 1; i++)
	{
		for (int j = 2; j <= m - 1; j++)
		{
			int temp_dr = down_right[i - 1][j] + up_right[i][j - 1] + down_left[i][j + 1] + up_left[i + 1][j];
			int temp_ur = down_right[i][j - 1] + up_right[i + 1][j] + down_left[i - 1][j] + up_left[i][j + 1];
			ans = max(ans, temp_dr);
			ans = max(ans, temp_ur);
		}
	}

	//output
	printf("%d\n", ans);
	return 0;
}