Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- //#define anc(x) (pa[x]=pa[pa[x]]=pa[pa[pa[x]]]=pa[pa[pa[pa[x]]]]=pa[pa[pa[pa[pa[x]]]]]=pa[pa[pa[pa[pa[pa[x]]]]]]=pa[pa[pa[pa[pa[pa[pa[x]]]]]]])
- #define anc(x) (x==pa[x] ? x : (pa[x]==pa[pa[x]] ? pa[x] : (pa[pa[x]]==pa[pa[pa[x]]] ? pa[pa[x]] : (pa[pa[pa[x]]]==pa[pa[pa[pa[x]]]] ? pa[pa[pa[x]]] : (pa[pa[pa[pa[x]]]]==pa[pa[pa[pa[pa[x]]]]] ? pa[pa[pa[pa[x]]]] : (pa[pa[pa[pa[pa[x]]]]]==pa[pa[pa[pa[pa[pa[x]]]]]] ? pa[pa[pa[pa[pa[x]]]]] : (pa[pa[pa[pa[pa[pa[x]]]]]]==pa[pa[pa[pa[pa[pa[pa[x]]]]]]] ? pa[pa[pa[pa[pa[pa[x]]]]]] : (pa[pa[pa[pa[pa[pa[pa[x]]]]]]]==pa[pa[pa[pa[pa[pa[pa[pa[x]]]]]]]] ? pa[pa[pa[pa[pa[pa[pa[x]]]]]]] : pa[pa[pa[pa[pa[pa[pa[pa[x]]]]]]]]))))))))
- #define join(x,y) ((x=anc(x))!=(y=anc(y)) && (rk[x]<rk[y]&&(x^=y^=x^=y),pa[y]=x,rk[x]!=rk[y]||++rk[x]))
- using namespace std;
- typedef unsigned ll;
- constexpr ll N = 12525, M = 1252525;
- struct edge{ll u,v,w;} E[M];
- bool operator<(const edge& a, const edge& b){return a.w<b.w;}
- ll pa[N],rk[N],n,m,sum,CC;
- /*#include <string>
- void show(string x, int d){
- for(int i = 0; i < d; i++) {
- cout << '(' << x << "==pa[" << x << "] ? " << x << " : ";
- x = "pa["+x+"]";
- if(i==d-1) cout << x;
- }
- for(int i = 0; i < d; i++) cout << ')';
- }*/
- signed main(){
- //show("x",8);
- //return 0;
- ios_base::sync_with_stdio(0), cin.tie(0);
- while(cin >> n >> m, n||m){
- for(int i = 1; i <= n; i++) pa[i]=i, rk[i]=0;
- for(int i = 0; i < m; i++) cin >> E[i].u >> E[i].v >> E[i].w;
- sort(E,E+m);
- sum = 0, CC = n;
- for(int i = 0; i < m; i++) if(join(E[i].u,E[i].v)) sum += E[i].w, CC--;
- if(CC == 1)
- cout << sum << '\n';
- else
- cout << -1 << '\n';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment