From: http://www.cnblogs.com/DSChan/p/4862019.html
The topic said to find two non-intersecting paths, in fact, can also be equivalent to (from) to (N,m) the two disjoint path.
If you are looking for only one, then return to the most classic dp[i][j] = max (dp[i-1][j],dp[i][j-1]) + a[i][j].
Now find two, you can start the array to four-dimensional.
Dp[x1][y1][x2][y2] = max{
DP[X1][Y1-1][X2][Y2-1],
Dp[x1-1][y1][x2-1][y2],
DP[X1-1][Y1][X2][Y2-1],
DP[X1][Y1-1][X2-1][Y2]
}
+ a[x1][y1] + a[x2][y2]
To two paths can not intersect, that is, dp[x][y][x][y] is an illegal state, judge can not go through this state.
The simplest method is to make x2>x1, because Dp[x1][y1][x2][y2] is equivalent to dp[x2][y2][x1][y1].
Since M and N are up to 50, the four-dimensional array is too large, and there is a lot of repetition and waste.
Brain repair, two notes at the same time, they pass the same number of people at the same time, according to this can be reduced dimension.
D[I][X1][X2] indicates that the x-coordinate of the two strips of step i is X1 and X2 respectively, then y1=i-x1+2,y2=i-x2+2.
So we can get the DP equation.
D[I][X1][X2] = max{d[i-1][x1][x2], d[i-1][x1-1][x2], d[i-1][x1][x2-1], d[i-1][x1-1][x2-1]} + a[x1][i-x1+2] + a[x2][i-x2 +2]
Note that the answer D[n+m-2][n][n] is to be counted (as this is "illegal state")
- #include <iostream>
- #include <cassert>
- #include <cstdio>
- #include <cstring>
- #include <algorithm>
- #include <cmath>
- #include <string>
- #include <iterator>
- #include <cstdlib>
- #include <vector>
- #include <stack>
- #include <map>
- #include <set>
- Using namespace std;
- #define REP (i,f,t) for (int i = (f), _end_= (t); I <= _end_; ++i)
- #define REP2 (I,F,T) for (int i = (f), _end_= (t); i < _end_; ++i)
- #define DEP (I,F,T) for (int i = (f), _end_= (t); I >= _end_; i.)
- #define DEP2 (I,F,T) for (int i = (f), _end_= (t); i > _end_; i.)
- #define CLR (c, X) memset (c, X, sizeof (c))
- typedef Long long int64;
- const int INF = 0x5f5f5f5f;
- Const Double eps = 1e-8;
- //*****************************************************
- int d[100][55][55];
- int a[55][55];
- inline int max (int i,int J,int k,int l)
- {
- return Max (Max (i,j), Max (k,l));
- }
- int main ()
- {
- int n,m;
- scanf ("%d%d", &n,&m);
- Rep (I,1,n) Rep (j,1,m) scanf ("%d", &a[i][j]);
- Rep (I,1,n+m-2) Rep (X1,max (1,i+2-m), Min (n,i+1))
- {
- int y1 = i-x1 + 2;
- Rep (X2,max (x1+1,i+2-m), Min (n,i+1))
- {
- int y2 = i-x2 + 2;
- D[I][X1][X2] = max (d[i-1][x1-1][x2-1], d[i-1][x1][x2-1],
- D[I-1][X1-1][X2],D[I-1][X1][X2])
- + a[x1][y1] + a[x2][y2];
- }
- }
- D[n+m-2][n][n] = D[n+m-3][n-1][n];
- cout<<d[n+m-2][n][n]<<endl; ///Direct output D[N+M-3][N-1][N]
- return 0;
- }
code1169 Pass the note