![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include<bits/stdc++.h> 2 using namespace std; 3 int pre[5005],n,m,ans,cnt; 4 struct lhy 5 { 6 int x,y,cost; 7 }glq[200005]; 8 9 void init() 10 { 11 for(int i=1;i<=5005;i++) pre[i]=i; 12 } 13 int find(int t) 14 { 15 while(t!=pre[t]) t=pre[t]=pre[pre[t]]; 16 return t; 17 } 18 bool cmp(lhy a,lhy b) 19 { 20 return a.cost<b.cost; 21 } 22 void kruskal() 23 { 24 sort(glq+1,glq+m+1,cmp); 25 for(int i=1;i<=m;i++) 26 { 27 int lhy_zz=find(glq[i].x),glq_zz=find(glq[i].y); 28 if(lhy_zz==glq_zz) continue; 29 ans+=glq[i].cost; 30 pre[lhy_zz]=glq_zz; 31 cnt++; 32 if(cnt==n-1) break; 33 } 34 } 35 int main() 36 { 37 init(); 38 scanf("%d%d",&n,&m); 39 for(int i=1;i<=m;i++) 40 { 41 scanf("%d%d%d",&glq[i].x,&glq[i].y,&glq[i].cost); 42 } 43 kruskal(); 44 printf("%d",ans); 45 return 0; 46 }
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include<bits/stdc++.h> 2 using namespace std; 3 int cost[105][105],n,c,minn[105]; 4 bool s[105]; 5 int main() 6 { 7 memset(minn,999999,sizeof(minn)); 8 scanf("%d",&n); 9 for(int i=1;i<=n;i++) 10 { 11 for(int j=1;j<=n;j++) 12 { 13 int a; 14 scanf("%d",&a); 15 cost[i][j]=cost[j][i]=a; 16 } 17 } 18 minn[1]=0; 19 for(int i=1;i<=n;i++) 20 { 21 int k=0; 22 for(int j=1;j<=n;j++) 23 { 24 if(s[j]==0&&minn[j]<minn[k]) k=j; 25 } 26 s[k]=1; 27 for(int j=1;j<=n;j++) 28 { 29 if(s[j]==0&&minn[j]>cost[k][j]+minn[k]) minn[j]=cost[k][j]+minn[k]; 30 } 31 } 32 for(int i=1;i<=n;i++) c+=minn[i]; 33 printf("%d",c); 34 return 0; 35 }