【思路】
与求最短路差不多的dp
f[i][j] 代表在j点并且已经经过了状态为表示的这些点的最小代价
遍历在可能的状态i中,没有经过j点的所有点取加上这些点与j的代价的最小值即可,即:
f[i][j] = min(f[i][j], f[i - (1 << j)][k] + graph[k][j])
【边界条件】
想出来了就没啥边界条件了。。。
import java.util.*;
import java.math.*;
public class Main{
void run(){
int n = jin.nextInt();
int[][] graph = new int[n][n];
for (int i = 0; i < n ; i++){
for (int j = 0 ; j < n ; j++){
graph[i][j] = jin.nextInt();
}
}
res = hamilton(graph, n);
System.out.println(res);
}
int hamilton(int[][] graph, int n){
int [][] f = new int[1 << n][n];
for (int i = 0; i < (1 << n); i++){
Arrays.fill(f[i], Integer.MAX_VALUE / 2);
}
f[1][0] = 0;
for (int i = 1 ; i < (1 << n); i++){
for (int j = 0 ; j < n ; j++){
if (((i >> j) & 1) == 1){
for (int k = 0 ; k < n ; k ++){
if ((((i - (1 << j))>>k )& 1 ) == 1){
f[i][j] = Math.min(f[i][j], f[i - (1 << j)][k] + graph[k][j]);
}
}
}
}
}
return f[(1 << n) -1 ][n-1];
}
private int res = 0;
private Scanner jin = new Scanner(System.in);
public static void main(String[] args) throws Exception{new Main().run();}
}