用prime算法,kruscal 可能会超时
prime算法找路径的时候开辟一个数组记录路径。
#include <iostream>
#include <string.h>
#include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;
#define MAXN 1000 + 1
#define inf 1e20
int n;
bool vis[MAXN];
int pre[MAXN];
struct Node
{
int x, y;
double p;
}node[MAXN];
struct Edge
{
int u, v, next;
}edge[1000 * MAXN];
int head[MAXN], e;
void add(int u, int v)
{
edge[e].u = u;
edge[e].v = v;
edge[e].next = head[u];
head[u] = e++;
}
double c[MAXN][MAXN];
void init()
{
e = 0;
memset(head, -1, sizeof(head));
}
int mul(int x)
{
return x * x;
}
double distanceto(int i, int j)
{
return sqrt(mul(node[i].x - node[j].x) + mul(node[i].y - node[j].y));
}
double sum;
int ed[MAXN];
double dis[MAXN];
int fa[MAXN];
void prime()
{
sum = 0;
memset(vis, false, sizeof(vis));
for (int i = 0; i < n; i++)
{
dis[i] = c[0][i];
fa[i] = 0;
}
dis[0] = 0;
vis[0] = true;
for (int i = 1; i < n; i++)
{
double mi = inf;
int s;
for (int j = 0; j < n; j++)
{
if (!vis[j] && mi > dis[j])
{
mi = dis[j];
s = j;
}
}
sum += dis[s];
vis[s] = true;
add(fa[s], s);
add(s, fa[s]);
for (int j = 0; j < n; j++)
{
if (!vis[j] && dis[j] > c[s][j])
{
dis[j] = c[s][j];
fa[j] = s;
}
}
}
}
double mx;
void dfs(int u)
{
vis[u] = true;
mx = max(mx, node[u].p);
for (int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].v;
if (!vis[v] && c[u][v] != -1)
{
vis[v] = true;
dfs(v);
}
}
}
void solve()
{
double ans = 0;
for (int i = 0; i < n; i++)
{
for (int j = head[i]; j != -1; j = edge[j].next)
{
int u = edge[j].u, v = edge[j].v;
memset(vis, false, sizeof(vis));
double temp = c[u][v];
c[u][v] = -1;
c[v][u] = -1;
mx = 0;
dfs(u);
double temp1 = mx;
mx = 0;
dfs(v);
double temp2 = mx;
c[u][v] = temp;
c[v][u] = temp;
ans = max(ans, (temp1 + temp2) / (sum - c[u][v]));
}
}
printf("%.2lf\n", ans);
}
void input()
{
int t;
scanf("%d", &t);
while (t--)
{
scanf("%d", &n);
init();
for (int i = 0; i < n; i++)
{
scanf("%d %d %lf", &node[i].x, &node[i].y, &node[i].p);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i != j)
{
c[i][j] = distanceto(i, j);
}
}
}
prime();
solve();
}
}
int main()
{
input();
return 0;
}