Tranvick

mst

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