Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- vector<int> a(100000),size(100000);
- struct cmp{
- bool operator()(const array<int,3> &a,const array<int,3> &b){
- return a[2]>b[2];
- }
- };
- int findroot(int x){
- return x==a[x]? x:(a[x]=findroot(a[x]));
- }
- int main(){
- ios_base::sync_with_stdio(false);
- cin.tie(0);
- int m,n,aroot,broot,tt;
- long long sum;
- array<int,3> temp;
- priority_queue<array<int,3>,vector<array<int,3>>,cmp> path;
- while(cin>>n>>m){
- sum=0;
- for(int i=0;i<n;i++) a[i]=i,size[i]=1;
- for(int i=0;i<m;i++){
- cin>>temp[0]>>temp[1]>>temp[2];
- path.emplace(temp);
- }
- while(!path.empty()){
- temp=path.top();
- path.pop();
- aroot=findroot(temp[0]);
- broot=findroot(temp[1]);
- if(aroot==broot) continue;
- if(size[aroot]<size[broot]) swap(aroot,broot);
- size[aroot]+=size[broot];
- a[broot]=aroot;
- sum+=temp[2];
- }
- aroot=findroot(0);
- if(size[aroot]==n) cout<<sum<<'\n'; else cout<<"-1\n";
- }
- return 0;
- }
- /*
- Zero Judge a129. 最小生成樹
- https://zerojudge.tw/ShowProblem?problemid=a129
- 2024 June 16
- AC (0.4s, 6.4MB)
- */
Advertisement
Add Comment
Please, Sign In to add comment