首页 > 搜索 > DFS搜索 > hdu 2686 Matrix-动态规划-[解题报告]C++
2014
02-13

hdu 2686 Matrix-动态规划-[解题报告]C++

Matrix

问题描述 :

Yifenfei very like play a number game in the n*n Matrix. A positive integer number is put in each area of the Matrix.
Every time yifenfei should to do is that choose a detour which frome the top left point to the bottom right point and than back to the top left point with the maximal values of sum integers that area of Matrix yifenfei choose. But from the top to the bottom can only choose right and down, from the bottom to the top can only choose left and up. And yifenfei can not pass the same area of the Matrix except the start and end.

输入:

The input contains multiple test cases.
Each case first line given the integer n (2<n<30)
Than n lines,each line include n positive integers.(<100)

输出:

The input contains multiple test cases.
Each case first line given the integer n (2<n<30)
Than n lines,each line include n positive integers.(<100)

样例输入:

2
10 3
5 10
3
10 3 3
2 5 3
6 7 10
5
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9

样例输出:

28
46
80

Click here

多线程DP,第一次看到这个名词。

其实也还好,其实就是多个进程同时进行。

题意 :从(1,1)走到(N,N),每次只能向下或者向右走,然后在走回(1,1)每次只能向上或者向左走。然后每个点上都有一个值,问你途径所能获得的值最大是多少,并且每个点只能走一次。

思路 : 从(1,1)走出两条路来,开一个四维状态保存两个点的坐标。即 : DP[x1][y1][x2][y2];然后就开始DP了。

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int MAXN = 33;
const int INF = 9999999;

int dp[MAXN][MAXN][MAXN][MAXN];
int maze[MAXN][MAXN];
int N;
int dir[4][4] = {1,0,1,0,1,0,0,1,0,1,1,0,0,1,0,1};

int dfs(int x1,int y1,int x2,int y2)
{
      if (maze[x1][y1] == -1 || maze[x2][y2] == -1)return 0;
      if (x1 + y1 == N + N)return maze[N][N];
      if (dp[x1][y1][x2][y2] != -1)return dp[x1][y1][x2][y2];
      if (x1 == x2 && y1 == y2 && x1 + y1 > 2)return 0;
      int ans = 0;
      for (int i = 0;i < 4;i++)
      {
            int a = x1 + dir[i][0];
            int b = y1 + dir[i][1];
            int c = x2 + dir[i][2];
            int d = y2 + dir[i][3];
            int temp = dfs(a,b,c,d);
            ans = max(ans,temp);
      }
      return dp[x1][y1][x2][y2] = ans + maze[x1][y1] + maze[x2][y2];
}


int solve()
{
      memset(dp,-1,sizeof(dp));
      return dfs(1,1,1,1) - maze[1][1];
}

int main()
{
      while (scanf("%d",&N) != EOF)
      {
            memset(maze,-1,sizeof(maze));
            for (int i = 1;i <= N;i++)
                  for (int j = 1;j <= N;j++)
                  scanf("%d",&maze[i][j]);
            printf("%d\n",solve());
      }
      return 0;
}

解题转自:http://blog.csdn.net/danceonly/article/details/11694095