标签:
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=3001
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4642 Accepted Submission(s): 1531
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <string> 5 #include <cmath> 6 #include <vector> 7 #include <algorithm> 8 using namespace std; 9 #define INF 0x3f3f3f 10 int n, m; 11 int mp[11][11], dp[60000][11]; 12 int fun(int pos){ 13 return int(pow(3.0, pos)); 14 } 15 int main(){ 16 while(scanf("%d%d", &n, &m) != EOF){ 17 int a, b, c; 18 for(int i = 1; i <= n; i++){ 19 for(int j = 1; j <= n; j++){ 20 if(i == j) mp[i][j] = 0; 21 else mp[i][j] = -1; 22 } 23 } 24 for(int i = 1; i <= m; i++){ 25 scanf("%d%d%d", &a, &b, &c); //注意重边。 26 if(mp[a][b] == -1) mp[a][b] = mp[b][a] = c; 27 else mp[a][b] = mp[b][a] = min(mp[a][b], c); 28 } 29 for(int i = 0; i < (fun(n)); i++){ 30 for(int j = 1; j <= n; j++) dp[i][j] = -1; 31 } 32 for(int pos = 1; pos <= n; pos++) dp[fun(pos-1)][pos] = 0; 33 34 for(int i = 0; i < (fun(n)); i++){ 35 for(int j = 1; j <= n; j++){ 36 if(dp[i][j] == -1) continue; 37 for(int k = 1; k <= n; k++){ 38 if(mp[j][k] == -1) continue; //如果不连通 39 int tpos = i; 40 for(int ii = 1; ii < k; ii++) tpos /= 3; 41 tpos = tpos%3; //找到那一位。 42 if(tpos == 2) continue; //这个点已经走了两次了,不能再经过了 43 if(dp[i+fun(k-1)][k] == -1) dp[i+fun(k-1)][k] = dp[i][j] + mp[j][k]; 44 if(dp[i+fun(k-1)][k] >= dp[i][j] + mp[j][k]) dp[i+fun(k-1)][k] = dp[i][j] + mp[j][k]; 45 } 46 } 47 } 48 int sum = 0; 49 for(int i = 0; i < n; i++) sum += int(pow(3.0, i)); 50 int Min = INF; 51 //sum是每个位上正好为1的状态,从sum开始循环。 52 for(int i = sum; i < fun(n); i++){ 53 for(int j = 1; j <= n; j++){ 54 bool flag = true; 55 int temp = i, r; 56 while(temp){ 57 r = temp%3; 58 if(r == 0){ 59 flag = false; break; 60 } 61 temp /= 3; 62 } 63 if(flag == false) continue; //判断是否有位上为0,这样的状态是不满足条件的。 64 if(dp[i][j] <= Min && dp[i][j] != -1) Min = dp[i][j]; 65 } 66 } 67 printf("%d\n",Min == INF?-1:Min); 68 } 69 return 0; 70 }
hdu3001 Travelling 旅行商问题 状态压缩DP
标签:
原文地址:http://www.cnblogs.com/titicia/p/4354830.html