1. 程式人生 > 其它 >正則基礎(複習+學習)

正則基礎(複習+學習)

根據貪心,在建樹時優先選擇長度小的邊

通過並查集判斷兩個點是否已聯通,如果已聯通,則跳過,如果為聯通,則連線 (因為是樹,所以僅有一條路徑)

P3366 【模板】最小生成樹 - 洛谷 | 電腦科學教育新生態 (luogu.com.cn)

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int N=5005,M=200005;
 4 int n,m,ans;
 5 int f[N];
 6 struct node
 7 {
 8     int from,to,le;
 9 };
10 node e[M];
11 int cmp(node x,node y)
12 { 13 return x.le<y.le; 14 } 15 int find(int x) 16 { 17 if(x==f[x])return x; 18 else return f[x]=find(f[x]); 19 } 20 int main() 21 { 22 cin>>n>>m; 23 for(int i=1;i<=n;++i)f[i]=i; 24 for(int i=1;i<=m;++i) 25 { 26 cin>>e[i].from>>e[i].to>>e[i].le;
27 } 28 sort(e+1,e+m+1,cmp); 29 for(int i=1;i<=m;++i) 30 { 31 int fro=e[i].from,t=e[i].to; 32 if(find(fro)!=find(t)) 33 { 34 ans+=e[i].le; 35 f[find(fro)]=f[find(t)]; 36 } 37 } 38 int fa=find(e[1].from); 39 for(int
i=1;i<=n;++i) 40 { 41 if(fa!=find(i)) 42 { 43 cout<<"orz"; 44 return 0; 45 } 46 } 47 cout<<ans; 48 return 0; 49 }