Tranvick

MST

Feb 3rd, 2012
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.62 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #define N 11111
  4. #define M 222222
  5.  
  6. using namespace std;
  7.  
  8. struct tree{
  9.     int x,y,z;
  10.     bool operator < (const tree & q) const{
  11.         return z<q.z;
  12.     }
  13. } t[N];
  14.  
  15. int p[N],n,m;
  16.  
  17. int dsu_get(int x){
  18.     return x==p[x]?x:p[x]=dsu_get(p[x]);
  19. }
  20.  
  21. inline int dsu_unite(int a,int b,int w){
  22.     a=dsu_get(a);
  23.     b=dsu_get(b);
  24.     if (a!=b){
  25.         p[a]=b;
  26.         cout<<a<<" "<<b<<" "<<w<<endl;
  27.     }
  28. }
  29.  
  30. int main(){
  31.     cin>>n>>m;
  32.     for (int i=1;i<=n;i++) p[i]=i;
  33.     for (int i=1;i<=m;i++) cin>>t[i].x>>t[i].y>>t[i].z;
  34.     sort(t+1,t+m+1);
  35.     for (int i=1;i<=m;i++) dsu_unite(t[i].x,t[i].y,t[i].z);
  36.     return 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment