bingxuan9112

毒瘤define版DSU

Jun 23rd, 2019
557
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. //#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]]]]]]])
  4. #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]]]]]]]]))))))))
  5. #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]))
  6.  
  7. using namespace std;
  8. typedef unsigned ll;
  9. constexpr ll N = 12525, M = 1252525;
  10.  
  11. struct edge{ll u,v,w;} E[M];
  12. bool operator<(const edge& a, const edge& b){return a.w<b.w;}
  13. ll pa[N],rk[N],n,m,sum,CC;
  14. /*#include <string>
  15. void show(string x, int d){
  16.     for(int i = 0; i < d; i++) {
  17.         cout << '(' << x << "==pa[" << x << "] ? " << x << " : ";
  18.         x = "pa["+x+"]";
  19.         if(i==d-1) cout << x;
  20.     }
  21.     for(int i = 0; i < d; i++) cout << ')';
  22. }*/
  23. signed main(){
  24.     //show("x",8);
  25.     //return 0;
  26.     ios_base::sync_with_stdio(0), cin.tie(0);
  27.     while(cin >> n >> m, n||m){
  28.         for(int i = 1; i <= n; i++) pa[i]=i, rk[i]=0;
  29.         for(int i = 0; i < m; i++) cin >> E[i].u >> E[i].v >> E[i].w;
  30.         sort(E,E+m);
  31.         sum = 0, CC = n;
  32.         for(int i = 0; i < m; i++) if(join(E[i].u,E[i].v)) sum += E[i].w, CC--;
  33.         if(CC == 1)
  34.             cout << sum << '\n';
  35.         else
  36.             cout << -1 << '\n';
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment