秦始皇要修建连通所有城市的路,一共有N个点以及各个点的坐标和人口。修建很多条路使N个城市连通,但是可以使其中一条路的修建费用为0。在修建费用最小的前提下,使得A/B最大。A指费用为0的路所连通的两个城市的人口和,B指除修建费用为0的路之外的所以路之和。
解题思路:因为要是整体的修建费用最小,必定要求他的最小生成树。但是可以使生成树中的一条边的费用为0,这样就不能简单的光求最小生成树。因为可以使连接某两个城市的路修建费用为0,所以可以枚举所有两个城市的组合。这样A的值就固定下来了,为了使得A/B最大。则需要删去这两个城市的连通路径中最长的边,使得B值越小。因为在这两个城市直接连边是不需要费用的。这样的话就和求次小生成树的算法有点像了。一开始把问题像的简单了,所以直接用了kruskal。但是求次小生成树还是prime算法比较方便。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<cmath>
using namespace std;
const int maxx = 1005;
struct node
{
int from, to;
double len;
node(int a, int b, double c)
{
from = a, to = b, len = c;
}
node() {}
bool operator<(const node &b)
{
return len < b.len;
}
}edge[maxx*maxx];
int x[maxx], y[maxx], people[maxx];
int fa[maxx];
double cost[maxx][maxx];
int cnt, n;
vector<pair<int, double>>G[maxx];
vector<int> path;
void addedge(int a, int b)
{
double now = sqrt(double((x[a] - x[b])*(x[a] - x[b]) + (y[a] - y[b])*(y[a] - y[b])));
edge[++cnt] = node(a, b, now);
}
int find(int now)
{
if (fa[now] == now)
return now;
else
return fa[now] = find(fa[now]);
}
double kru()
{
double res = 0;
for (int i = 1; i <= n; i++)
G[i].clear();
for (int i = 1; i <= cnt; i++)
{
int xx = find(edge[i].from), yy = find(edge[i].to);
if (xx != yy)
{
res += edge[i].len;
fa[xx] = yy;
G[edge[i].from].push_back(make_pair(edge[i].to, edge[i].len));
G[edge[i].to].push_back(make_pair(edge[i].from, edge[i].len));
}
}
return res;
}
void dfs(int v, int fa)
{
path.push_back(v);
for (int i = 0; i < G[v].size(); i++)
{
int to = G[v][i].first;
double now = G[v][i].second;
if (to != fa)
{
for (int j = 0; j < path.size(); j++)
{
int eric = path[j];
cost[to][eric] = cost[eric][to] = max(now, cost[eric][v]);
}
dfs(to, v);
}
}
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
cnt = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
fa[i] = i;
for (int i = 1; i <= n; i++)
scanf("%d%d%d", &x[i], &y[i], &people[i]);
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++)
{
addedge(i, j);
}
sort(edge + 1, edge + 1 + cnt);
double sum = kru();
double ans = 0;
path.clear();
memset(cost, 0, sizeof(cost));
dfs(1, -1);
for (int i = 1; i <= cnt; i++)
{
int s = edge[i].from;
int t = edge[i].to;
double tmp = sum - cost[s][t];
ans = max(ans, (people[s] + people[t] + 0.0) / tmp);
}
printf("%0.2f\n", ans);
}
return 0;
}
本人愚见,如有不足,欢迎指点~~