Luo Gu P1004 take several squares
Topic links: Luo Gu P1004 take several squares
Algorithms Tags: 动态规划(DP)
topic
Title Description
With \ (N \ times N \) squares FIG \ ((N \ Le. 9) \) , wherein the grid we fill some positive integer, while the other is placed in the box numbers 0 . Shown (see examples) as shown below:
A
0 0 0 0 0 0 0 0
0 0 13 0 0 6 0 0
0 0 0 0 7 0 0 0
0 0 0 14 0 0 0 0
0 21 0 0 0 4 0 0
0 0 15 0 0 0 0 0
0 14 0 0 0 0 0 0
0 0 0 0 0 0 0 0
B
Someone from the upper left corner of the graph (\ A) \ point of view, you can walk down, you can also go to the right until you reach the bottom right corner of \ (B \) points. On the way through, he can the number of squares removed (after removal checkered number becomes 0).
The person from the \ (A \) point \ (B \) Points on down twice, try to find such a path 2, so as to obtain the maximum sum of the number.
Input Format
A first act input integer \ (N \) (represented by \ (N \ times N \) squares FIG), each line has three next integer, indicates the position of the first two, the third number for the position put on the number. 0 indicates the end of the single line input.
Output Format
Only output an integer representing the two paths obtained and maximum.
Sample input and output
Input # 1
8
2 3 13
2 6 6
3 5 7
4 4 14
5 2 21
5 6 4
6 3 15
7 2 14
0 0 0
Output # 1
67
answer:
Four-dimensional dynamic programming, because the data subject \ (N ≤ 9 \) , so do not worry about time-out or hyperspace, the specific transfer equation is as follows:
f[i][j][k][l] = max{
// i,k描述两条路径横坐标情况
// j,l描述两条路径纵坐标情况
f[i - 1][j][k - 1][l],
f[i][j - 1][k][l - 1],
f[i - 1][j][k][l - 1],
f[i][j - 1][k - 1][l])
}+ map[i][j] + map[k][l];
Note that while, since the number after each point on this point will be cleared, so when the two paths through the same point in time to subtract a sum \ (map [i] [j ] (= = map [k] [l] ) \) to ensure that the number on this point can only be calculated once.
Also in the time to pay attention to read while()
the exit condition.
AC Code
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int N = 10;
int n, map[N][N], f[N][N][N][N];
int getmax(int a, int b, int c, int d)
{
int ans = max(a, max(b, max(c, d)));
return ans;
}
int main()
{
scanf("%d", &n);
int x, y, z;
while(1)
{
scanf("%d%d%d", &x, &y, &z);
if (x == 0 && y == 0 && z == 0)
break;
map[x][y] = z;
}
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= n; j ++ )
for (int k = 1; k <= n; k ++ )
for (int l = 1; l <= n; l ++ )
{
f[i][j][k][l] =
getmax(f[i - 1][j][k - 1][l],
f[i][j - 1][k][l - 1],
f[i - 1][j][k][l - 1],
f[i][j - 1][k - 1][l])
+ map[i][j] + map[k][l];
if (i == k && j == l)
f[i][j][k][l] -= map[i][j];
}
printf("%d\n", f[n][n][n][n]);
return 0;
}