很强悍的算法,至今,仍旧迷迷糊糊。先将看懂的代码贴上来。
牛人讲解:http://blog.csdn.net/lhshaoren/article/details/7526480
以下代码是转自牛人的。
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> using namespace std; #define MAXN 21 const double INF = 1<<23; struct Node{ int x, y, z; }node[MAXN]; double d[MAXN][1<<MAXN]; int n; double min(double x, double y){ return x < y ? x : y; } void init() { scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d %d %d",&node[i].x,&node[i].y,&node[i].z); } double dis(Node &a, Node &b){ return sqrt(double(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)+(a.z-b.z)*(a.z-b.z)); } void solve(){ for(int i=0; i<n; i++){ for(int s=0; s<(1<<(i+1)); s++){ if(s == 0) d[i][s] = 0; else d[i][s] = INF; if(s & (1<<i)){ for(int j=0; j<i; j++){ if(s & (1<<j)){ d[i][s] = min(d[i][s], dis(node[i], node[j])+d[i-1][s^(1<<i)^(1<<j)]); } } } else if(i != 0) d[i][s] = d[i-1][s]; } } } int main(){ init(); solve(); printf("%.3lf\n",d[n-1][(1<<n)-1]); return 0; }
测试数据:
Input:
20
1 2 3
1 1 1
5 6 2
4 7 8
2 3 1
1 4 7
2 5 8
3 6 9
1 2 5
2 3 6
4 5 2
7 8 5
4 5 1
-1 2 3
-1 -9 -7
0 0 0
100 0 0
9 5 1
7 5 3
5 5 5
Output:
119.076