
Unidirectional TSP
This problem deals with finding a minimal path through a grid of points while traveling only from left to right.
Given an m*n matrix of integers, you are to write a program that computes a path of minimal weight. A path starts anywhere in column 1 (the first column) and consists of a sequence of steps terminating in column n (the last column). A step consists of traveling from column i to column i+1 in an adjacent (horizontal or diagonal) row. The first and last rows (rows 1 and m) of a matrix are considered adjacent, i.e., the matrix ``wraps'' so that it represents a horizontal cylinder. Legal steps are illustrated below.
The weight of a path is the sum of the integers in each of the n cells of the matrix that are visited.
For example, two slightly different 5*6 matrices are shown below (the only difference is the numbers in the bottom row).
The minimal path is illustrated for each matrix. Note that the path for the matrix on the right takes advantage of the adjacency property of the first and last rows.
For each specification the number of rows will be between 1 and 10 inclusive; the number of columns will be between 1 and 100 inclusive. No path's weight will exceed integer values representable using 30 bits
# include<stdio.h>
# include<string.h>
# include<iostream>
using namespace std;
# define inf 0xffffff
int map[][];
int p[][];
int s[];
int main()
{
int m,n,i,j;
while(scanf("%d%d",&m,&n)!=EOF)
{
memset(p,-,sizeof(p));
for(i=; i<=m; i++)
for(j=; j<=n; j++)
scanf("%d",&map[i][j]);
for(j=n-; j>=; j--) //从后往前计算,因为要打印路径
for(i=; i<=m; i++)
{
int b=i,a,c,d,e=-; //a,b,c分别为向左上,向左,向左下的坐标
if(i>=) a=i-;
else a=m;
if(i<m) c=i+;
else c=;
d = min(min(map[a][j+],map[b][j+]),map[c][j+]); //取最小值
map[i][j] += d;
if(d==map[a][j+]) e=a;
if(d==map[b][j+]&&(e==-||(e!=-&&b<e))) e=b; //e的作用当两行的数字相同时去小的一个
if(d==map[c][j+]&&(e==-||(e!=-&&c<e))) e=c;
p[i][j] = e; //记录路径
}
int flag = ;
int sum =inf;
for(i=; i<=m; i++)
if(map[i][] < sum)
{
sum = map[i][];
flag=i;
}
printf("%d",flag);
flag = p[flag][];
for(i=; i<=n && flag != -; i++)
{
printf(" %d",flag);
flag = p[flag][i];
}
printf("\n%d\n",sum);
}
return ;
}