经典问题:哈密尔顿路径 DP~

View Code
1 #include <cstdio>
2 #include <cstring>
3
4  #define MIN(a,b) (a < b ? a : b)
5
6  using namespace std;
7
8 const int NC = 20;
9 const int INF = (1 << 20);
10
11 int dp[1<<NC][NC];
12
13 int limit[NC];
14 int length[NC][NC];
15
16 int main()
17 {
18 int nv;
19 int nl;
20 int va;
21 int vb;
22
23 while (scanf("%d %d",&nv,&nl) != EOF)
24 {
25 memset(limit,0,sizeof(limit));
26
27 for (int i = 0;i < nv;i++)
28 for (int j = 0;j < nv;j++)
29 scanf("%d",&length[i][j]);
30
31 for (int i = 0;i < nl;i++)
32 {
33 scanf("%d %d",&va,&vb);
34 limit[vb] |= (1 << va);
35 }
36
37 int lim = (1 << nv);
38 for (int i = 0;i < lim;i++)
39 for (int j = 0;j < nv;j++)
40 dp[i][j] = INF;
41
42 dp[1][0] = 0;
43
44 for (int i = 1;i < lim;i++)
45 for (int j = 0;j < nv;j++)
46 for (int k = 0;k < nv;k++)
47 if (!(i & (1 << k)) && length[j][k] != -1 && (i & limit[k]) == limit[k])
48 dp[i|(1<<k)][k] = MIN(dp[i|(1<<k)][k],dp[i][j] + length[j][k]);
49
50 int ans = (1 << 20);
51 for (int i = 0;i < nv;i++)
52 {
53 int tmp = dp[lim-1][i];
54 if (ans > tmp)
55 ans = tmp;
56 }
57 printf("%d\n",ans == INF ? -1 : ans);
58 }
59 return 0;
60 }