用的堆优化的prim算法写的,之前把prim与dijkstra弄混了,prim是不用更新边的
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <cmath>
#include <queue>
using namespace std;
const int INF = 1 << 30;
const int NIL = -1;
const int MAXN = 105;
int vis[MAXN];
double d[MAXN];
int head[20005];
int n;
int cnt;
struct Edge {
int to, next;
double w;
Edge() {}
Edge(int _to, double _w) :to(_to), w(_w) {}
friend bool operator<(const Edge& a, const Edge& b)
{
return a.w > b.w;
}
} edge[20005];
struct Coor {
int x, y;
} coor[MAXN];
void add(int u, int v, double w)
{
edge[cnt].to = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt++;
}
void prim(int n)
{
priority_queue<Edge> q;
for (int i = 0; i < n; ++i)
vis[i] = false;
double ans = 0.0;
vis[0] = true;
for (int i = head[0]; i != NIL; i = edge[i].next)
q.push(edge[i]);
Edge t;
int u, v;
double w;
int count = 0;
while (!q.empty() && count < n - 1)
{
t = q.top();
q.pop();
if (vis[t.to])
continue;
vis[t.to] = true;
ans += t.w;
++count;
u = t.to;
for (int i = head[u]; i != NIL; i = edge[i].next)
{
v = edge[i].to;
if (!vis[v])
q.push(edge[i]);
}
}
if (count == n - 1)
printf("%.1lf\n", ans * 100);
else
puts("oh!");
}
int main(void)
{
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
/*cin.tie(0);
ios::sync_with_stdio(false);*/
int T, c;
scanf("%d", &T);
while (T--)
{
scanf("%d", &c);
for (int i = 0; i < c; ++i)
scanf("%d%d", &coor[i].x, &coor[i].y);
cnt = 0;
memset(head, -1, 2 * sizeof(int) * c * c);
for (int i = 0; i < c - 1; ++i)
for (int j = i + 1; j < c; ++j)
{
int dist = (coor[j].x - coor[i].x) * (coor[j].x - coor[i].x) + (coor[j].y - coor[i].y) * (coor[j].y - coor[i].y);
if (100 <= dist && dist <= 1000000)
{
double s = sqrt(dist);
add(i, j, s);
add(j, i, s);
}
}
prim(c);
}
return 0;
}