Given the coordinates of n points, we need to find the shortest path to link these points.
Idea: Prime + minimal spanning tree
Analysis: Given the coordinates of n points, it is required to find the shortest path. Obviously, you can use Prime to create the minimum spanning tree. Here, you must first find the length of each edge.
Code:
[Cpp]
# Include <algorithm>
# Include <iostream>
# Include <cstdio>
# Include <cstring>
# Include <cmath>
Using namespace std;
# Define maxn110
# Define INF 0 xFFFFFFF
Int t, n;
Double G [MAXN] [MAXN];
Double lowcost [MAXN];
Double ans;
Int vis [MAXN];
Struct Point {
Double x;
Double y;
} P [MAXN];
Void init (){
Memset (G, 0, sizeof (G ));
For (int I = 0; I <n; I ++ ){
For (int j = 0; j <n; j ++ ){
If (I = j)
Continue;
Double tmp_x, tmp_y;
Tmp_x = (p [I]. x-p [j]. x) * (p [I]. x-p [j]. x );
Tmp_y = (p [I]. y-p [j]. y) * (p [I]. y-p [j]. y );
G [I] [j] = sqrt (tmp_x + tmp_y );
}
}
}
Void Prime (){
Int pos;
Double min;
Memset (vis, 0, sizeof (vis ));
Vis [0] = 1;
Ans = 0;
For (int I = 0; I <n; I ++)
Lowcost [I] = G [0] [I];
For (int I = 0; I <n; I ++ ){
Min = INF;
For (int j = 0; j <n; j ++ ){
If (! Vis [j] & lowcost [j] <min ){
Min = lowcost [j];
Pos = j;
}
}
If (min = INF)
Break;
Ans + = min;
Vis [pos] = 1;
For (int j = 0; j <n; j ++ ){
If (! Vis [j] & lowcost [j]> G [pos] [j])
Lowcost [j] = G [pos] [j];
}
}
Printf ("%. 2lf \ n", ans );
}
Int main (){
// Freopen ("input.txt", "r", stdin );
Scanf ("% d", & t );
While (t --){
Scanf ("% d", & n );
For (int I = 0; I <n; I ++)
Scanf ("% lf", & p [I]. x, & p [I]. y );
Init ();
Prime ();
If (t)
Printf ("\ n ");
}
Return 0;
}