标签:
分阶段的DAG,注意字典序的处理和路径的保存。
定义状态d[i][j]为从i,j 出发到最后一列的最小花费,转移的时候只有三种,向上,向下,或平移。
#include<bits/stdc++.h> using namespace std; const int maxm = 11; const int maxn = 101; int G[maxm][maxn]; const int INF = 1e9; int d[maxm][maxn]; int path[maxn][maxn]; int main() { //freopen("in.txt","r",stdin); int m,n; while(~scanf("%d%d",&m,&n)){ for(int i = 0; i < m; i++) for(int j = 0; j < n ;j++){ scanf("%d",G[i]+j); } int ans = INF,head = 0; for(int i = 0; i < m; i++) d[i][n-1] = G[i][n-1]; if(n == 1){ for(int i = 0; i < m; i++){ if(d[i][0]<ans) { ans = d[i][0]; head = i; } } }else { for(int j = n-2; j >= 0; j--){ for(int i = 0; i < m; i++){ int nxt[] = {i,i+1,i-1}; if(i == 0) nxt[2] = m-1; if(i == m-1) nxt[1] = 0; sort(nxt,nxt+3); d[i][j] = d[nxt[0]][j+1]; path[i][j] = nxt[0]; for(int k = 1; k < 3; k++){ int t = d[nxt[k]][j+1]; if(t < d[i][j]){ d[i][j] = t; path[i][j] = nxt[k]; } } d[i][j] += G[i][j]; if(j == 0 && d[i][j] < ans) { ans = d[i][j]; head = i; } } } } printf("%d",head+1); for(int i = path[head][0],j = 1; j < n; i = path[i][j], j++){ printf(" %d",i+1); } printf("\n%d\n",ans); } return 0; }
UVA116 Unidirectional TSP 单向TSP
标签:
原文地址:http://www.cnblogs.com/jerryRey/p/4726562.html