洛谷 P3366 【模板】最小生成树

题目描述

如题,给出一个无向图,求出最小生成树,如果该图不连通,则输出orz

输入输出格式

输入格式:

第一行包含两个整数N、M,表示该图共有N个结点和M条无向边。(N<=5000,M<=200000)

接下来M行每行包含三个整数Xi、Yi、Zi,表示有一条长度为Zi的无向边连接结点Xi、Yi

输出格式:

输出包含一个数,即最小生成树的各边的长度之和;如果该图不连通则输出orz

输入输出样例

输入样例#1:
4 5
1 2 2
1 3 2
1 4 3
2 3 4
3 4 3
输出样例#1:
7

说明

时空限制:1000ms,128M

数据规模:

对于20%的数据:N<=5,M<=20

对于40%的数据:N<=50,M<=2500

对于70%的数据:N<=500,M<=10000

对于100%的数据:N<=5000,M<=200000

样例解释:

所以最小生成树的总边权为2+2+3=7

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 
 5 using namespace std;
 6 const int N=200001;
 7 
 8 int n,m;
 9 int f[N];
10 int now=1;
11 
12 struct node{
13     int u,v,w;
14 }E[200001];
15 
16 int cmp(const node & a,const node & b)
17 {
18     return a.w<b.w;
19 }
20 
21 inline int find(int x)
22 {
23     if(f[x]!=x)
24         f[x]=find(f[x]);
25     return f[x];    
26 }
27 
28 inline void un(int x,int y)
29 {
30     int fx=find(x);
31     int fy=find(y);
32     f[fx]=fy;
33 }
34 
35 int main()
36 {
37     scanf("%d%d",&n,&m);
38     for(int i=1;i<=n;i++)
39        f[i]=i;
40     for(int i=1;i<=m;i++)
41     {
42         scanf("%d%d%d",&E[i].u,&E[i].v,&E[i].w);
43     }
44     int ans=0;
45     
46     sort(E+1,E+m+1,cmp);
47     
48     int tot=0;
49     for(int i=1;i<=m;i++)
50     {
51         if(find(E[i].u)!=find(E[i].v))
52         {
53             ans+=E[i].w;
54             tot++;
55             un(find(E[i].u),find(E[i].v));    
56         }
57         if(tot==n-1) break;
58     }
59     if(tot!=n-1)
60     {
61         printf("orz");
62     }
63     else printf("%d",ans);
64     
65     return 0;
66 }

46行的m写成了n,调了好长时间,蠢

原文地址:https://www.cnblogs.com/lyqlyq/p/6853632.html