Morass

Uf-Other

Mar 6th, 2016
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <cstdio>
  5.  
  6. using namespace std;
  7.  #define DEB printf("DEB!\n");
  8. #define D(X) cout<<"  "<<#X": "<<X<<endl;
  9. typedef pair<int,int> ii;
  10. typedef vector<int> vi;
  11. typedef vector<pair<int,ii> > vii;
  12. class UnionFind{
  13.     vi p,rank;
  14. public:
  15.     UnionFind(int m){
  16.         for(int i=0;i<1000004;i++){
  17.             rank.push_back(0),p.push_back(i);
  18. //            rank[i]=0;p[i]=i;
  19.         }
  20.     }
  21.     int findset(int i){return p[i]==i?i:p[i]=findset(p[i]);}
  22.     bool issameset(int i,int j){return findset(i)==findset(j);}
  23.     void unionset(int i,int j){
  24.         if(!issameset(i,j)){
  25.             int x=findset(i),y=findset(j);
  26.             if(rank[x]>rank[y]) p[y]=x;
  27.             else{
  28.                 if(rank[x]<rank[y]) p[x]=y;
  29.                 else{rank[x]++,p[y]=x;}
  30.             }
  31.         }
  32.     }
  33. };
  34. bool endline=false;
  35. int main(){
  36.     int n;
  37.     while(!cin.eof()){
  38.         int i,n;cin>>n;
  39.         vii edgelist;
  40.         edgelist.clear();
  41.         int initial=0;
  42.         for(i=0;i<n-1;i++){
  43.             int u,v,x;cin>>u>>v>>x;
  44.             initial+=x;
  45.         }
  46.         int k;cin>>k;
  47.         for(i=0;i<k;i++){
  48.             int u,v,w;
  49.             cin>>u>>v>>w;
  50.             u--;v--;
  51.             edgelist.push_back(make_pair(w,ii(u,v)));
  52.         }
  53.         int m;cin>>m;
  54.         for(i=0;i<m;i++){
  55.             int u,v,w;
  56.             cin>>u>>v>>w;u--;v--;
  57.             edgelist.push_back(make_pair(w,ii(u,v)));
  58.         }
  59.  
  60.         int mst=0;
  61.         sort(edgelist.begin(),edgelist.end());
  62.         UnionFind UF(n);
  63.         for(i=0;i<m+k;i++){
  64.             pair<int,ii> front=edgelist[i];
  65.             if(!UF.issameset(front.second.first,front.second.second)){
  66.                 mst+=front.first;
  67.                 UF.unionset(front.second.first,front.second.second);
  68.             }
  69.         }
  70.         if(endline==false)  endline=true;
  71.         else    cout<<endl;    
  72.         cout<<initial<<endl<<mst<<endl;
  73.     }
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment