UVa 116 - Unidirectional TSP

简单的动态规划(递推),要能够打印最小权值对应的最小字典序路径;

MIN 定义中‘<’写成了‘>’导致一次WA。。

另外求最小权值对应的最小下标那里写的很乱。

# include <stdio.h>

# define MIN(X,Y) ((X)<(Y) ? (X):(Y))

int f[12][105];
int p[12][105];

int col, row;

int main()
{
int i, j, ans, t, x;

while (~scanf("%d%d", &row, &col))
{
for (i = 0; i < row; ++i)
for (j = 0; j < col; ++j)
{
scanf("%d", &f[i][j]);
}

for (j = col-2; j >= 0; --j)
for (i = 0; i < row; ++i)
{
x = (f[(i+1)%row][j+1] < f[(i-1+row)%row][j+1]) ? ((i+1)%row) : ((i-1+row)%row);
if (f[(i+1)%row][j+1] == f[(i-1+row)%row][j+1]) x = MIN((i+1)%row, (i-1+row)%row);
if (f[x][j+1] > f[i][j+1] || (f[x][j+1] == f[i][j+1] && i < x)) x = i;
f[i][j] += f[x][j+1];
p[i][j] = x;
}

for (ans = (1<<30)+1, i = 0; i < row; ++i)
if (f[i][0] < ans) {ans = f[i][0]; t = i;}

printf("%d", t+1);
for (j = 0; j < col - 1; ++j)
{
printf(" %d", p[t][j]+1);
t = p[t][j];
}

printf("\n%d\n", ans);
}

return 0;
}

你可能感兴趣的:(uva)