Main topic:
in the Matrix M*n, from (the peak) point to (M,n) point, and then from (M,n) point to (the) point, the route passed by the classmate's best value, ask each point can only go once.
Analysis:
① we can only think of it as two people at the same time from the point, go to (m,n) point.
② because it can only go in the previous two directions so no matter what the route , the number of steps taken from (M,n) must be the same. F[< Span class= "token MD md-underlined-text" >x1]< Span class= "token MD md-bracket-start" >[y1]< Span class= "token linkref" >[x2][y2]" (indicates that a person is currently walking in ( X1,Y1) A person walking in (x2,y2)) that means x1+y1 = X2+y2.
< Span class= "token linkref" > ③ This problem, the open four-dimensional array is too large to time out. Know the same number of steps taken at the same time. Then we can set up a three-dimensional array f [i][ X1][x2 : I for step I (or I moment), first person in X1 line, first Two people in the X2 line, the students passed the best value of kindness. Be careful to find out: The number of steps to walk is known, the number of steps down (i.e. X1, x2) is known, < Span class= "token ref-end" > Then the number of steps to the right can also be known y1= i-x1; y2 = i-x2; In fact F[i][x1< Span class= "token MD md-bracket-end" >][x2" Has hinted at the location of two people (X1, i-x1), (x2, i-x2), represented and four-dimensional array f[ X1][y1][x2][y2". &NBSP;
Also note: My array starts from (p). If you start with (0,0), just change the border a little bit.
#include <iostream>#include<cstdio>#include<string.h>#include<math.h>using namespacestd;intT, M, N, a[ -][ -], f[ Max][ -][ -];intMAX1 (intAintBintCintd) {a=Max (A, b); C=Max (c, D); A=Max (A, c); returnA;}voiddp () { for(inti =3; i < m+n; i++) { for(intX1 =1; X1 <= N && x1 <= I-1; x1++) { for(intx2 =1; X2 < n && X2 < I1; x2++) { intY1 = i-X1; inty2 = i-x2; if(y1 = = y2)Continue;//if y1, y2 is different then x1,x2 must also be different. Then two people wouldn't have gone the same way.F[I][X1][X2] = Max1 (f[i-1][X1][X2], f[i-1][x1][x2-1], f[i-1][x1-1][x2], f[i-1][x1-1][x2-1]) +a[x1][y1]+A[x2][y2]; } } }}intMain () {CIN>>T; while(t--) {memset (A,0,sizeof(a)); scanf ("%d%d", &n, &m); for(inti =1; I <= N; i++) for(intj =1; J <= M; J + +) scanf ("%d", &A[i][j]); Memset (F,0,sizeof(f)); DP (); printf ("%d\n", f[m+n-1][n][n-1]); } return 0;}
View Code
Two-path dynamic programming nyoj61