例题9-4 单向TSP UVa116

1.题目描述:点击打开链接

2.解题思路:本题属于多阶段决策问题,可以利用动态规划解决。本题中每个阶段都有3个决策:直行,右上,右下。如果设d(i,j)表示从格子(i,j)出发到最后一列的最小开销,同时利用next数组记录找到最优解时的行号。(记录前要对行号进行排序)

3.代码:

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;

#define maxn 100+10
#define INF 9999999
int a[maxn][maxn];
int d[maxn][maxn];
int Next[maxn][maxn];
int m, n;
int main()
{
	//freopen("test.txt", "r", stdin);
	while (scanf("%d%d", &m, &n) == 2 && m&&n)
	{
		for (int i = 0; i < m;i++)
		for (int j = 0; j < n; j++)
		{
			scanf("%d", &a[i][j]);
		}
		int ans = INF, first = 0;
		for (int j = n - 1; j >= 0; j--)//逆推
		{
			for (int i = 0; i < m; i++)
			{
				if (j == n - 1)d[i][j] = a[i][j];
				else
				{
					int rows[3] = { i, i - 1, i + 1 };//记录三个决策用到的行号
					if (i == 0)rows[1] = m - 1;
					if (i == m - 1)rows[2] = 0;
					sort(rows, rows + 3);//对行号排序,以便于找到字典序最小的
					d[i][j] = INF;
					for (int k = 0; k < 3; k++)
					{
						int v = d[rows[k]][j + 1] + a[i][j];
						if (v < d[i][j]){ d[i][j] = v; Next[i][j] = rows[k]; }
					}
				}
				if (j == 0 && d[i][j] < ans){ ans = d[i][j]; first = i; }//找到最终的答案
			}
		}
		printf("%d", first + 1);
		for (int i = Next[first][0], j = 1; j < n; i = Next[i][j], j++)//顺着Next数组走
			printf(" %d", i + 1);
		printf("\n%d\n", ans);
	}
	return 0;
}

你可能感兴趣的:(动态规划,uva)