做了 第一道 最小生成树 hehe
Time Limit: 1 Sec Memory Limit: 64 MB
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 (X_i, Y_i) on the plane (0 <= X_i <=
1,000,000; 0 <= Y_i <= 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: X_i and Y_i
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
HINT
INPUT DETAILS:
Four farms at locations (1,1), (3,1), (2,3), and (4,3). Farms 1 and 4 are
connected by a road.
OUTPUT DETAILS:
Connect farms 1 and 2 with a road that is 2.00 units long, then connect
farms 3 and 4 with a road that is 2.00 units long. This is the best we can
do, and gives us a total of 4.00 unit lengths.
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<functional>
using namespace std;
typedef long long ll;
int n,m;
struct node
{
int from,to;
double val;
}edge[1000006];
int cnt;
int pos[1003][2];
bool cmp(node x,node y)
{
return x.val<y.val;
}
int fa[1003];
int find(int x)
{
if(fa[x]!=x) fa[x]=find(fa[x]);
return fa[x];
}
void unnion(int x,int y)
{
x=find(x),y=find(y);
fa[x]=y;
}
int main()
{
int i,j;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++) fa[i]=i;
for(i=1;i<=n;i++)
{
scanf("%d%d",&pos[i][0],&pos[i][1]);
for(j=1;j<i;j++)
{
edge[++cnt].from=i;
edge[cnt].to=j;
ll p=pos[i][0]-pos[j][0];
ll q=pos[i][1]-pos[j][1];
edge[cnt].val=sqrt(p*p+q*q);
}
}
int kkk=0;
for(i=1;i<=m;i++)
{
int x,y;
scanf("%d%d",&x,&y);
unnion(x,y);
kkk++;
}
sort(edge+1,edge+cnt+1,cmp);
double sum=0.0;
for(i=1;i<=cnt;i++)
{
if(kkk==n-1) break;
if(find(edge[i].from)!=find(edge[i].to))
{
sum+=edge[i].val;
kkk++;
unnion(edge[i].from,edge[i].to);
}
}
printf("%.2lf",sum);
return 0;
}
/*
4 1
1000000 1000000
3000000 1000000
2000000 3000000
4000000 3000000
1 4
*/