Advertisement
NgJaBach

Kruskal

Jan 8th, 2022
1,137
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4. typedef long long int ll;
  5. //#define isvowel(a) (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
  6. #define pb push_back
  7. #define mp make_pair
  8. #define fi first
  9. #define se second
  10. #define gcd __gcd
  11. #define getl(s) getline(cin, s);
  12. #define setpre(x) fixed << setprecision(x)
  13. #define mset(a) memset(a, 0, sizeof(a))
  14. #define endl '\n'
  15. const int N=200050,M=1000000007;
  16. const ll INF=1e18+7;
  17. int cha[N],cha_size[N];
  18. int find_cha(int u){
  19.     if(cha[u]==u) return u;
  20.     return cha[u]=find_cha(cha[u]);
  21. }
  22. void European_Union(int u,int v){
  23.     int a,b;
  24.     a=find_cha(u);
  25.     b=find_cha(v);
  26.     if(cha_size[a]<cha_size[b]) swap(a,b);
  27.     cha[b]=a;
  28.     cha_size[a]+=cha_size[b];
  29.     return;
  30. }
  31. int main(){
  32.     ios_base::sync_with_stdio(NULL); cin.tie(nullptr); cout.tie(nullptr);
  33. //    freopen(".inp","r",stdin);
  34. //    freopen(".out","w",stdout);
  35.     int n,m,x,y,z;
  36.     ll sum=0;
  37.     vector<pair<int,pair<int,int> > >gay;
  38.     cin>>n>>m;
  39.     for(int i=1;i<=n;++i){
  40.         cha[i]=i;
  41.         cha_size[i]=1;
  42.     }
  43.     for(int i=0;i<m;++i){
  44.         cin>>x>>y>>z;
  45.         gay.pb(mp(z,mp(x,y)));
  46.     }
  47.     sort(gay.begin(),gay.end());
  48.     for(int i=0;i<m;++i){
  49.         x=gay[i].se.fi;
  50.         y=gay[i].se.se;
  51.         z=gay[i].fi;
  52.         if(find_cha(x)!=find_cha(y)){
  53.             European_Union(x,y);
  54.             sum+=z;
  55.         }
  56.     }
  57.     cout<<sum;
  58.     return 0;
  59. }
  60. /*
  61. ==================================+
  62. INPUT:                            |
  63. ------------------------------    |
  64.  
  65. ------------------------------    |
  66. ==================================+
  67. OUTPUT:                           |
  68. ------------------------------    |
  69.  
  70. ------------------------------    |
  71. ==================================+
  72. */
Advertisement
RAW Paste Data Copied
Advertisement