[题目链接]
http://poj.org/problem?id=2728
[算法]
0/1分数规划 + 最小生成树
[代码]
在本题中,prim算法的时间复杂度优于kruskal算法,且实现较为容易,因此,笔者程序中使用的是prim算法
#include <algorithm> #include <bitset> #include <cctype> #include <cerrno> #include <clocale> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <exception> #include <fstream> #include <functional> #include <limits> #include <list> #include <map> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stdexcept> #include <streambuf> #include <string> #include <utility> #include <vector> #include <cwchar> #include <cwctype> #include <stack> #include <limits.h> using namespace std; #define MAXN 1010 const double eps = 1e-7; const double INF = 1e50; int i,j,n; double l,r,mid,ans; double dist[MAXN][MAXN],cost[MAXN][MAXN]; double x[MAXN],y[MAXN],h[MAXN]; inline double prim(double mid) { int i,j,p; double mn,res = 0; static double d[MAXN]; static bool visited[MAXN]; for (i = 1; i <= n; i++) { d[i] = INF; visited[i] = false; } d[1] = 0; for (i = 1; i < n; i++) { p = 0; mn = INF; for (j = 1; j <= n; j++) { if (!visited[j] && d[j] < mn) { mn = d[j]; p = j; } } visited[p] = true; for (j = 1; j <= n; j++) { if (!visited[j]) d[j] = min(d[j],1.0 * cost[p][j] - mid * dist[p][j]); } } for (i = 1; i <= n; i++) res += d[i]; return res; } int main() { while (scanf("%d",&n) && n) { for (i = 1; i <= n; i++) scanf("%lf%lf%lf",&x[i],&y[i],&h[i]); for (i = 1; i <= n; i++) { for (j = i + 1; j <= n; j++) { dist[i][j] = dist[j][i] = 1.0 * sqrt(1.0 * (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j])); cost[i][j] = cost[j][i] = 1.0 * abs(h[i] - h[j]); } } l = 0.0; r = 100.00; while (r - l > eps) { mid = (l + r) / 2.00; if (prim(mid) >= 0) { ans = mid; l = mid; } else r = mid; } printf("%.3f ",ans); } return 0; }