076

Zero Judge a129. 最小生成樹

076
Jun 16th, 2024
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. vector<int> a(100000),size(100000);
  4. struct cmp{
  5.     bool operator()(const array<int,3> &a,const array<int,3> &b){
  6.         return a[2]>b[2];
  7.     }
  8. };
  9. int findroot(int x){
  10.     return x==a[x]? x:(a[x]=findroot(a[x]));
  11. }
  12. int main(){
  13.     ios_base::sync_with_stdio(false);
  14.     cin.tie(0);
  15.     int m,n,aroot,broot,tt;
  16.     long long sum;
  17.     array<int,3> temp;
  18.     priority_queue<array<int,3>,vector<array<int,3>>,cmp> path;
  19.     while(cin>>n>>m){
  20.         sum=0;
  21.         for(int i=0;i<n;i++) a[i]=i,size[i]=1;
  22.         for(int i=0;i<m;i++){
  23.             cin>>temp[0]>>temp[1]>>temp[2];
  24.             path.emplace(temp);
  25.         }
  26.         while(!path.empty()){
  27.             temp=path.top();
  28.             path.pop();
  29.             aroot=findroot(temp[0]);
  30.             broot=findroot(temp[1]);
  31.             if(aroot==broot) continue;
  32.             if(size[aroot]<size[broot]) swap(aroot,broot);
  33.             size[aroot]+=size[broot];
  34.             a[broot]=aroot;
  35.             sum+=temp[2];
  36.         }
  37.         aroot=findroot(0);
  38.         if(size[aroot]==n) cout<<sum<<'\n'; else cout<<"-1\n";
  39.     }
  40.     return 0;
  41. }
  42. /*
  43. Zero Judge a129. 最小生成樹
  44. https://zerojudge.tw/ShowProblem?problemid=a129
  45. 2024 June 16
  46. AC (0.4s, 6.4MB)
  47. */
Advertisement
Add Comment
Please, Sign In to add comment