AcWing 91. 最短Hamilton路径-java
原题链接
中等
作者:
Astarion
,
2021-02-23 20:52:32
,
所有人可见
,
阅读 296
import java.io.*;
import java.util.Arrays;
class Main {
//注意:INF不能设为最大int,相加时会溢出到负值
static final int INF = 0x3fffffff;
static final int N = 20;
static int[][] w = new int[N][N];
static void insert(int a, int b, int v) {
w[a][b] = w[b][a] = v;
}
//第一维表示状态,第二维表示当前点
static int[][] f = new int[1 << N][N];
static {
for (int i = 0; i < 1<<N; i++) Arrays.fill(f[i], INF);
f[1][0] = 0;
}
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String[] strs = in.readLine().split(" ");
int n = Integer.parseInt(strs[0]);
for (int i = 0; i < n; i++) {
strs = in.readLine().split(" ");
for (int j = 0; j < n; j++) {
int v = Integer.parseInt(strs[j]);
insert(i, j, v);
}
}
in.close();
isr.close();
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter out = new BufferedWriter(osw);
//遍历每种状态
for (int i = 1; i < 1<<n; i++)
//遍历每个点
for (int j = 0; j < n; j++)
//如果当前状态有这个点
if (((i >> j) & 1) == 1) {
//求前驱状态pre
int pre = i - (1 << j);
//对于前驱状态,遍历每个点
for (int k = 0; k < n; k++)
//如果前驱状态的k点可以走到j点
if (((pre >> k) & 1) == 1)
f[i][j] = Math.min(f[i][j], f[pre][k] + w[k][j]);
}
out.write(f[(1 << n) - 1][n - 1] + "");
out.flush();
out.close();
osw.close();
}
}