题意
传送门 POJ 2728
题解
分数规划问题,二分求解,即求满足 ∑ c o s t i ∑ l e n i ≤ x \frac{\sum cost_{i}}{\sum len_{i}}\leq x ∑leni∑costi≤x 的 x x x 最小值。不等式变形 ∑ ( c o s t i − x × l e n i ) ≤ 0 \sum (cost_{i}-x\times len_{i})\leq 0 ∑(costi−x×leni)≤0 若存在满足上式的一棵生成树,则可以收缩上界。显然,不等式右端的最小值可以通过求最小生成树进行求解。考虑到图中任一对节点间存在直接连边,图是稠密图,用堆优化的 P r i m Prim Prim 或者 K r u s k a l Kruskal Kruskal 复杂度为 O ( E l o g V ) = O ( n 2 l o g n ) O(ElogV)=O(n^2logn) O(ElogV)=O(n2logn),此时使用朴素的 P r i m Prim Prim 效果更好,复杂度为 O ( n 2 ) O(n^2) O(n2)。
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define eps 1e-5
#define inf 0x3f3f3f3f
#define maxn 1005
int n, x[maxn], y[maxn], z[maxn];
double mincost[maxn], len[maxn][maxn], cost[maxn][maxn], d[maxn][maxn];
bool used[maxn];
double prim(double m)
{
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
d[i][j] = d[j][i] = cost[i][j] - m * len[i][j];
}
}
for (int i = 0; i < n; i++)
{
mincost[i] = inf, used[i] = 0;
}
mincost[0] = 0;
double res = 0;
while (1)
{
int v = -1;
for (int u = 0; u < n; u++)
{
if (!used[u] && (v == -1 || mincost[u] < mincost[v]))
{
v = u;
}
}
if (v == -1)
{
break;
}
used[v] = 1, res += mincost[v];
for (int u = 0; u < n; u++)
{
mincost[u] = min(mincost[u], d[v][u]);
}
}
return res;
}
int main()
{
while (~scanf("%d", &n) && n)
{
for (int i = 0; i < n; i++)
{
scanf("%d%d%d", x + i, y + i, z + i);
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
double dx = x[i] - x[j], dy = y[i] - y[j];
len[i][j] = len[j][i] = sqrt(dx * dx + dy * dy), cost[i][j] = cost[j][i] = abs(z[i] - z[j]);
}
}
// 分数规划
double lb = 0, ub = inf;
while (ub - lb > eps)
{
double mid = (lb + ub) / 2;
if (prim(mid) <= 0)
ub = mid;
else
lb = mid;
}
printf("%.3lf\n", lb);
}
return 0;
}