close
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <queue> #include <math.h> #include <algorithm> using namespace std; struct edge { int a,b; double dis; bool operator < (const edge &s2) const { return dis > s2.dis; } }; struct point { double x,y; }; point P[105]; int root[105]; int find(int x) { if(x== root[x])return x; else return root[x]=find(root[x]); } int un (int a,int b) { int ra=find(a); int rb=find(b); if(ra != rb) { root[ra]=root[rb]; return 1; } return 0; } void init () { for(int i=0; i<105; i++) { root[i]=i; } } priority_queue<edge> pq; int main() { int test=0; scanf("%d",&test); string str; while(test--) { getchar(); getline(cin,str); int num=0; scanf("%d",&num); init(); for(int i=0; i<num; i++) { scanf("%lf%lf", &P[i].x, &P[i].y); } int edge_count=0; for(int i=0; i<num; i++) { for(int j=i+1; j<num; j++) { double len = sqrt(pow(P[i].x - P[j].x, 2) + pow(P[i].y - P[j].y, 2)); //printf("%f\n",len); pq.push( {i,j,len} ); } } edge E; int num2=0; double cost=0; while(num2+1<num && !pq.empty()) { E=pq.top(); pq.pop(); if(un(E.a,E.b)) { num2++; cost+=E.dis; } } printf("%.2f\n\n",cost); } }
#kruskal's 用到sort 和 dependent set
文章標籤
全站熱搜