题目
分析
- 首先连通图 肯定是树啦
- 不就是最小生成树吗
- 然后我们把一些已经存在的边赋值为0
- 跑出来就是ans
代码
1 #include <cmath>
2 #include <cstdio>
3 #include <cstring>
4 #include <iostream>
5 #include <algorithm>
6 #define ll long long
7 using namespace std;
8 struct sb
9 {
10 int x,y;
11 }a[2001];
12 struct A
13 {
14 int from,to; double val;
15 }e[1000001];
16 int map[1001][1001];
17 double calc(int x1,int x2)
18 {
19 double ans=sqrt((double)(a[x1].x-a[x2].x)*(a[x1].x-a[x2].x)+(double)(a[x1].y-a[x2].y)*(a[x1].y-a[x2].y));
20 return ans;
21 }
22 int fa[1001];
23 bool cmp(A a,A b){return a.val<b.val;}
24 int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
25 int main()
26 {
27 int n,m;
28 scanf("%d%d",&n,&m);
29 for (int i=1,xx,yy;i<=n;i++)
30 {
31 scanf("%d%d",&xx,&yy);
32 a[i].x=xx; a[i].y=yy;
33 }
34 int tot=0;
35 for (int i=1,x,y;i<=m;i++)
36 {
37 scanf("%d%d",&x,&y);
38 e[++tot].from=x; e[tot].to=y; e[tot].val=0;
39 map[x][y]=1;
40 }
41 for (int i=1;i<n;i++)
42 for (int j=i+1;j<=n;j++)
43 {
44 if (i==j||map[i][j]==1) continue;
45 e[++tot].from=i; e[tot].to=j; e[tot].val=calc(i,j);
46 }
47 sort(e+1,e+1+tot,cmp);
48 for (int i=1;i<=n;i++) fa[i]=i;
49 double ans=0;
50 int cnt=0;
51 for (int i=1;i<=tot&&cnt<n-1;i++)
52 {
53 int u=find(e[i].from),v=find(e[i].to);
54 if (u==v) continue;
55 ans+=e[i].val,cnt++,fa[u]=v;
56 }
57 printf("%.2f",ans);
58 return 0;
59 }