The problem is the simple application of the minimal spanning tree. At first, did not think of using the smallest spanning tree to do, think of is greedy, when known to use the smallest spanning tree to do, but also made a very serious mistake, is the time complexity of the estimate wrong, leading to the beginning dare not write, thinking of other methods. Think of it as a lesson.
The following is the code of the AC, with detailed comments, with a check set to judge the ring, the time complexity of Nlogn, the main time in the sort.
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath>using namespace std; class data//two points of the direct edge of public:int from, to; Beginning and ending double dis; Distance};d ata dis[15000]; At the most multilateral time, approximately 10000double xy[105][2];int par[105], N, m; Par for and check set int cmp (const data& A, const data& B)//Sort by distance from small to large row {return A.dis < B.dis;} int finds (int x)//And look up function {if (x = = Par[x]) return X;elsereturn par[x] = finds (Par[x]);} void join (int x, int y)//And check-set merge function {x = finds (x); y = finds (y); if (x! = y) par[y] = x;} Double Kru ()//kruskal algorithm {for (int i = 0; I <= n; i++)//Initialize and check set {par[i] = i;} Sort (dis, dis + M, CMP); Sort double ans = 0.0;for (int j = 0; J < m; J + +) {if (Finds (dis[j].from)! = Finds (dis[j].to))//judgment existence ring {ans + = Dis[j].dis ; Join (Dis[j].from, dis[j].to); Merge two points}}return ans;} int main () {while (scanf ("%d", &n)! = EOF) {m = 0;for (int i = 0; I &Lt N i++) {scanf ("%lf%lf", &xy[i][0], &xy[i][1]);} for (int j = 0; J < N; j + +)//find the distance between each two points {for (int k = j + 1; k < n; k++) {Dis[m].from = j;dis[m].to = k; Dis[m++].dis = sqrt (Pow ((xy[j][0]-xy[k][0]), 2) + POW ((xy[j][1]-xy[k][1]), 2);}} Double ans = Kru ();p rintf ("%.2lf\n", ans); Here in C + + submitted, if using g++, should be changed to%.2f}return 0;}
Hangzhou Electric Acm1162--eddy ' s picture~~ minimum spanning tree