UVa116 Unidirectional TSP
Test instructions: Given a matrix of n*m, requires starting from any row in the first column, each time along the right or bottom right or right up to the following column, and finally to the first row of the column m of the entire distance of the minimum value, and the requirement is the smallest dictionary order.
Analysis: The stage is obvious, a column is a stage, in a column of each state there are 3 decisions, right, bottom right, top right, directly update the minimum value on the line. Note that the title requires a minimum dictionary order, just at the beginning is a push, the definition of dp[i][j] for the first row in the J column, the minimum distance traveled, but found that the latter is difficult to find the smallest dictionary order scheme, the path is not good record, so wa .... Even if the path is recorded, reverse printing is not very convenient, Finally, the use of inverse push to solve the problem.
For this in the planning of the optimal value at the same time also requires to take the dictionary of the minimum scheme of the problem, choose the appropriate recursion order, the use of the array to directly record the path to eliminate the loop will be a viable choice, purple book above still speak very good.
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <
cmath> #define INF 0x3f3f3f3f #define LL Long long using namespace std;
int mat[30][110], dp[30][110], path[30][110];
int n, m; int main () {while (~SCANF ("%d%d", &n, &m)) {for (int i = 1; I <= n; i++) for (int j = 1; J <= M;
J + +) scanf ("%d", mat[i]+j);
Memset (DP, INF, sizeof (DP));
for (int i = 1; I <= n; i++) dp[i][m] = mat[i][m];
for (int j = m; j > 1; j--) {for (int i = 1; I <= n; i++) {int row[3] = {i-1, I, i+1};
if (i = = 1) row[0] = n;
if (i = = N) row[2] = 1;
Sort (row, row+3);
for (int x = 0; x < 3; + +) {int tmp = dp[i][j]+mat[row[x]][j-1];
if (TMP < dp[row[x]][j-1]) {dp[row[x]][j-1] = tmp; PATH[ROW[X]][J-1] = I
}}}} int cost = INF, R;
for (int i = 1; I <= n; i++) if (Cost > dp[i][1]) R = i, cost = dp[i][1];
printf ("%d", r);
for (int i = path[r][1], j = 1; j < M; J + +, I = Path[i][j]) printf ("%d", I);
printf ("\n%d\n", cost);
} return 0;
}