UVa 116 - Unidirectional TSP

题目链接:UVa 116 - Unidirectional TSP

动态规划

难点在打印字典序路径,我也是看了人家的代码。。

#include <iostream>

using namespace std;

const int inf = 0x7FFFFFFF;
const int MAX_M = 10 + 2;
const int MAX_N = 100 + 10;
int d[MAX_M][MAX_N];
int val[MAX_M][MAX_N];
int dis[MAX_M][MAX_N];
int m,n;

int dp(int i,int j)
{
    if(j >= n)
        return 0;
    if(d[i][j] != inf)
        return d[i][j];

    int _min = inf;
    int a,b,c;
    a = dp((i + 1) % m,j + 1);
    b = dp((i - 1 + m) % m,j + 1);
    c = dp(i,j + 1);
    int _dis = inf;
    _min = min(min(a,b),c);
    if(_min == b)
        _dis = (i - 1 + m) % m;
    if(_min == c)
        _dis = min(_dis,i);
    if(_min == a)
        _dis = min(_dis,(i + 1) % m);
    dis[i][j] = _dis;
    return d[i][j] = val[i][j] + _min;
}
int main()
{
    while(cin >> m >> n)
    {
        for(int i = 0;i < m;i++)
        {
            for(int j = 0;j < n;j++)
            {
                cin >> val[i][j];
                d[i][j] = inf;
            }
        }
        int _min_dis = inf;
        int beg;
        for(int i = 0;i < m;i++)
        {
            int k = dp(i,0);
            if(_min_dis > k)
            {
                _min_dis = k;
                beg = i;
            }
        }
        cout << beg + 1;
        beg = dis[beg][0];
        for(int i = 1;i < n;i++)
        {
            cout << " " << beg + 1;
            beg = dis[beg][i];
        }
        cout << endl;
        cout << _min_dis << endl;
    }
    return 0;
}


你可能感兴趣的:(UVa 116 - Unidirectional TSP)