我们假设图G是完全图,预先计算好所有边的权值并加入边集。
for(int i = 1; i<=N; ++i)
for(int j = i+1; j<=N; ++j){
edge[++cnt].x = i;
edge[cnt].y = j;
edge[cnt].w = cal_dis(i, j);
}
在读入输入数据已给的M条边时,直接进行并查集合并处理。
for(int i = 1; i<=M; ++i){
int x, y;
scanf("%d %d", &x, &y);
int fx = find(x);
int fy = find(y);
fa[fx] = fy;
}
再此基础上再跑一遍Kruskal算法,用贪心策略选边使整个图连通即可。以下是全部代码:
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
#define MaxN 1005
#define MaxM 1005
struct NODE{
double x, y;
}node[MaxN];
struct EDGE{
int x, y;
double w;
}edge[MaxN*MaxN];
int cnt;
double ans;
bool cmp(EDGE a, EDGE b){
return a.w<b.w;
}
int N, M;
int fa[MaxN];
double cal_dis(int x, int y){
double tmp = (double)(node[x].x-node[y].x)*(node[x].x-node[y].x);
tmp += (double)(node[x].y-node[y].y)*(node[x].y-node[y].y);
tmp = sqrt((double)tmp);
return tmp;
}
int find(int x){
return fa[x] == x ? fa[x] : fa[x] = find(fa[x]);
}
int main(){
scanf("%d %d", &N, &M);
for(int i = 1; i<=N; ++i) fa[i] = i;
for(int i = 1; i<=N; ++i) scanf("%lf %lf", &node[i].x, &node[i].y);
for(int i = 1; i<=N; ++i)
for(int j = i+1; j<=N; ++j){
edge[++cnt].x = i;
edge[cnt].y = j;
edge[cnt].w = cal_dis(i, j);
}
sort(edge+1, edge+1+cnt, cmp);
for(int i = 1; i<=M; ++i){
int x, y;
scanf("%d %d", &x, &y);
int fx = find(x);
int fy = find(y);
fa[fx] = fy;
}
for(int i = 1; i<=cnt; ++i){
int fx = find(edge[i].x);
int fy = find(edge[i].y);
if(fx == fy) continue;
ans += edge[i].w;
++M;
fa[fx] = fy;
}
printf("%.2lf\n", ans);
return 0;
}