Ultraviolet A 10034-Freckles

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.