Home TSP 问题
Post
Cancel

TSP 问题

TSP最短路径.png

输入:

1
2
3
4
5
4
0 30 6 4
6 5 0 20
30 0 5 10
4 10 20 0

输出:

1
30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <cmath>
using namespace std;
const int INF=0x3f3f3f3f;
const int N=2<<13;
int n;
int g[20][20],dp[20][N];
int main() {
    scanf("%d",&n);
    for(int i=0;i<n;++i)
        for(int j=0;j<n;++j)
            scanf("%d",&g[i][j]);
    for(int i=1;i<n;++i)
        dp[i][0]=g[i][0];
    for(int j=1;j<(1<<(n-1));++j){
        for(int i=0;i<n;++i){
            dp[i][j]=INF;
            for(int k=1;k!=n;++k)
                if((j>>(k-1))&1)
                    dp[i][j]=min(dp[i][j],dp[k][j^(1<<(k-1))]+g[i][k]);
        }
    }
    printf("%d\n",dp[0][(1<<(n-1))-1]);
    return 0;
}
This post is licensed under CC BY 4.0 by the author.