-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path908.cpp
More file actions
108 lines (99 loc) · 1.64 KB
/
908.cpp
File metadata and controls
108 lines (99 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include<bits/stdc++.h>
using namespace std;
struct node{
int u;
int key;
node(int u,int key){
this->u = u;
this->key = key;
}
bool operator < (const node& p) const{
return this->key > p.key ;
}
};
map<int,vector<int>> G;
map<pair<int,int>,int> edgeCost;
set<int> vertices;
map<int,int>key;
map<int,int>selected;
void clear(){
G.clear();
edgeCost.clear();
vertices.clear();
key.clear();
selected.clear();
}
void mst(int source){
priority_queue<node> q;
q.push(node(source,0));
key[source] = 0;
for(auto i:vertices){
if(i != source){
key[i] = INT_MAX;
}
}
while(!q.empty()){
node top = q.top();
q.pop();
for(auto i :G[top.u]){
if(!selected.count(i)){
if(key[i] > edgeCost[{top.u,i}]){
q.push(node(i,edgeCost[{top.u,i}]));
key[i] = edgeCost[{top.u,i}];
}
}
}
selected[top.u] = 1;
}
}
int main(){
int v,e;
int count = 0;
int t = 0;
while(cin>>v){
int cst = 0;
count++;
v = v-1;
while(v--){
int a,b,c;
cin>>a>>b>>c;
cst = cst + c;
}
if(t!=0) cout<<endl;
int m;
cin>>m;
while(m--){
int x,y,c;
cin>>x>>y>>c;
G[x].push_back(y);
G[y].push_back(x);
edgeCost[pair<int,int>(x,y)] = c;
edgeCost[pair<int,int>(y,x)] = c;
vertices.insert(x);
vertices.insert(y);
}
cin>>e;
while(e--){
int x,y;
int c;
cin>>x>>y>>c;
G[x].push_back(y);
G[y].push_back(x);
edgeCost[pair<int,int>(x,y)] = c;
edgeCost[pair<int,int>(y,x)] = c;
vertices.insert(x);
vertices.insert(y);
}
for(auto i: vertices){
mst(i);
break;
}
int sum = 0;
for(auto i:vertices){
sum += key[i];
}
cout<<cst<<endl<<sum<<endl;
clear();
t++;
}
}