Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <cstdio>
- using namespace std;
- #define DEB printf("DEB!\n");
- #define D(X) cout<<" "<<#X": "<<X<<endl;
- typedef pair<int,int> ii;
- typedef vector<int> vi;
- typedef vector<pair<int,ii> > vii;
- class UnionFind{
- vi p,rank;
- public:
- UnionFind(int m){
- for(int i=0;i<1000004;i++){
- rank.push_back(0),p.push_back(i);
- // rank[i]=0;p[i]=i;
- }
- }
- int findset(int i){return p[i]==i?i:p[i]=findset(p[i]);}
- bool issameset(int i,int j){return findset(i)==findset(j);}
- void unionset(int i,int j){
- if(!issameset(i,j)){
- int x=findset(i),y=findset(j);
- if(rank[x]>rank[y]) p[y]=x;
- else{
- if(rank[x]<rank[y]) p[x]=y;
- else{rank[x]++,p[y]=x;}
- }
- }
- }
- };
- bool endline=false;
- int main(){
- int n;
- while(!cin.eof()){
- int i,n;cin>>n;
- vii edgelist;
- edgelist.clear();
- int initial=0;
- for(i=0;i<n-1;i++){
- int u,v,x;cin>>u>>v>>x;
- initial+=x;
- }
- int k;cin>>k;
- for(i=0;i<k;i++){
- int u,v,w;
- cin>>u>>v>>w;
- u--;v--;
- edgelist.push_back(make_pair(w,ii(u,v)));
- }
- int m;cin>>m;
- for(i=0;i<m;i++){
- int u,v,w;
- cin>>u>>v>>w;u--;v--;
- edgelist.push_back(make_pair(w,ii(u,v)));
- }
- int mst=0;
- sort(edgelist.begin(),edgelist.end());
- UnionFind UF(n);
- for(i=0;i<m+k;i++){
- pair<int,ii> front=edgelist[i];
- if(!UF.issameset(front.second.first,front.second.second)){
- mst+=front.first;
- UF.unionset(front.second.first,front.second.second);
- }
- }
- if(endline==false) endline=true;
- else cout<<endl;
- cout<<initial<<endl<<mst<<endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment