Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 1204 | Accepted: 307 |
Description
Farmer John had just acquired several new farms! He wants to connect the farms with roads so that he can travel from any farm to any other farm via a sequence of roads; roads already connect some of the farms.
Each of the N (1 ≤ N ≤ 1,000) farms (conveniently numbered 1..N) is represented by a position (Xi, Yi) on the plane (0 ≤ Xi ≤ 1,000,000; 0 ≤ Yi ≤ 1,000,000). Given the preexisting M roads (1 ≤ M ≤ 1,000) as pairs of connected farms, help Farmer John determine the smallest length of additional roads he must build to connect all his farms.
Input
* Line 1: Two space-separated integers: N and M
* Lines 2..N+1: Two space-separated integers: Xi and Yi
* Lines N+2..N+M+2: Two space-separated integers: i and j, indicating that there is already a road connecting the farm i and farm j.
Output
* Line 1: Smallest length of additional roads required to connect all farms, printed without rounding to two decimal places. Be sure to calculate distances as 64-bit floating point numbers.
Sample Input
4 1 1 1 3 1 2 3 4 3 1 4
Sample Output
4.00
Source
- #include<iostream>
- #include <math.h>
- using namespace std;
- struct _point
- {
- double x,y;
- }p[1001];
- #define MAXN 1001
- #define inf 1000000000
- typedef double elem_t;
- double mat[MAXN][MAXN];
- elem_t prim(int n,elem_t mat[][MAXN]){
- elem_t min[MAXN],ret=0;
- int v[MAXN],i,j,k;
- for (i=0;i<n;i++)
- min[i]=inf,v[i]=0;
- for (min[j=0]=0;j<n;j++){
- for (k=-1,i=0;i<n;i++)
- if (!v[i]&&(k==-1||min[i]<min[k]))
- k=i;
- for (v[k]=1,ret+=min[k],i=0;i<n;i++)
- if (!v[i]&&mat[k][i]<min[i])
- min[i]=mat[k][i];
- }
- return ret;
- }
- int main()
- {
- int n,m,i,j,a,b;
- cin>>n>>m;
- for(i=0;i<=n;i++)
- for(j=0;j<=n;j++)
- mat[i][j]=inf;
- for(i=0;i<n;i++)
- {
- cin>>p[i].x>>p[i].y;
- }
- for(i=0;i<n;i++)
- for(j=0;j<n;j++)
- {
- if(i==j) continue;
- mat[i][j]=sqrt((p[i].x-p[j].x)*(p[i].x-p[j].x)+(p[i].y-p[j].y)*(p[i].y-p[j].y));
- }
- for(i=0;i<m;i++)
- {
- cin>>a>>b;
- mat[a-1][b-1]=mat[b-1][a-1]=0;
- }
- printf("%.2lf/n",prim(n,mat));
- return 0;
- }