(并查集和最小生成树)洛谷P1546 [USACO3.1]最短网络 Agri-Net

P1546 [USACO3.1]最短网络 Agri-Net

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int N=105;
 4 int n,tot;
 5 int fa[N];
 6 int read()
 7 {
 8     int x=0,f=1;char ch=getchar();
 9     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
10     while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}
11     return x*f;
12 }
13 struct edge
14 {
15     int u,v,w;
16 }e[N*N];
17 
18 int fd(int x)
19 {
20     return fa[x]=(x==fa[x])?x:fd(fa[x]);
21 }
22 void merge(int x,int y)
23 {
24     int fx=fd(x),fy=fd(y);
25     fa[fy]=fx;
26 }
27 int main()
28 {
29     scanf("%d",&n);
30     for(int i=1;i<=n;i++)fa[i]=i;
31     int w;
32     for(int i=1;i<=n;i++)
33     for(int j=1;j<=n;j++)
34     {
35         w=read();
36         if(w)e[tot++]=(edge){i,j,w};
37     }
38     sort(e,e+tot,[](edge &a,edge &b){return a.w<b.w;});
39     int ans=0,cnt=0;
40     for(int i=0;i<tot;i++)
41     {
42         int u=e[i].u,v=e[i].v,w=e[i].w;
43         if(cnt==n-1)break;
44         if(fd(u)!=fd(v))
45         {
46             merge(u,v);
47             ans+=w;
48             cnt++;
49         }
50     }
51     printf("%d\n",ans);
52     return 0;
53 }

 

posted @ 2021-12-18 16:08  matt-11  阅读(45)  评论(0)    收藏  举报