首页 > 代码库 > UVa 116 - Unidirectional TSP

UVa 116 - Unidirectional TSP

题目:给你一个n*m的数字表格,找到一条从左到右的路径,使得上面的数字和最小。

           (每次可以从(i,j),走到(i,j+1),(i+1,j),(i-1,j)可以越界。)

分析:dp,动态规划。因为要字典序最小,所以采用从右向左的方式dp;

           状态:f(i,j)表示走到(i,j)的最小和,则有转移方程:

           f(i,j)= min(f(i+1,j+1),f(i,j+1),f(i-1,j+1));

           记录路径输出即可。

说明:逆向dp保证字典序最小(后继最小),正向能保证每点前驱最小。

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>

using namespace std;

int maps[11][101];
int smap[11][101];
int fath[11][101];

int main()
{
	int n,m;
	while (~scanf("%d%d",&n,&m)) {
		for (int i = 1 ; i <= n ; ++ i)
		for (int j = 1 ; j <= m ; ++ j)
			scanf("%d",&maps[i][j]);
		
		memset(smap, 0, sizeof(smap));
		
		for (int i = m ; i >= 1 ; -- i)
		for (int j = 1 ; j <= n ; ++ j) {
			smap[j][i] = smap[j][i+1]+maps[j][i];
			fath[j][i] = j;
			if (j > 1 && smap[j][i] >= smap[j-1][i+1]+maps[j][i]) {
				smap[j][i] = smap[j-1][i+1]+maps[j][i];
				fath[j][i] = j-1;
			}
			if (j == n && smap[j][i] >= smap[1][i+1]+maps[j][i]) {
				smap[j][i] = smap[1][i+1]+maps[j][i];
				fath[j][i] = 1;
			}
			
			if (j < n && smap[j][i] > smap[j+1][i+1]+maps[j][i]) {
				smap[j][i] = smap[j+1][i+1]+maps[j][i];
				fath[j][i] = j+1;
			}
			if (j == 1 && smap[j][i] > smap[n][i+1]+maps[j][i]) {
				smap[j][i] = smap[n][i+1]+maps[j][i];
				fath[j][i] = n;
			}
		}
		
		int spa = 1;
		for (int i = 2 ; i <= n ; ++ i)
			if (smap[spa][1] > smap[i][1])
				spa = i;
		
		int min = smap[spa][1];
		for (int i = 1 ; i <= m ; ++ i) {
			if (i < m) printf("%d ",spa);
			else printf("%d\n%d\n",spa,min);
			spa = fath[spa][i];
		}
	}
	return 0;
}

UVa 116 - Unidirectional TSP