-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubset
54 lines (53 loc) · 943 Bytes
/
subset
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
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int parent[1001]={-1,};
int height[1001]={0};
int Find(int u){
if(parent[u]==-1) return u;
return Find(parent[u]);
}
bool Union(int u,int v){
//같은 그룹에 있다면 합병
//아니면 false 리턴
u=Find(u);v=Find(v);
cout<<u<<v<<'\n';
if(u==v) return false;
if(height[u]<height[v]) swap(u,v);
parent[v]=u;
if(height[u]==height[v]) height[u]++;
return true;
}
struct Edge{
int u,v;
int c;
bool operator<(Edge rhs){
return c<rhs.c;
}
};
vector<Edge> edge;
int main() {
int V,E;
cin>>V>>E;
for(int i=1;i<=V;i++)parent[i]=-1;
for(int i=0,u,v,c;i<E;i++){
cin>>u>>v>>c;
edge.push_back({u,v,c});
}
sort(edge.begin(),edge.end());
int ans=0,cnt=0;
for(auto e:edge){
int u=e.u,v=e.v,c=e.c;
cout<<u<<v<<c;
cout<<"?";
if(Union(u,v)){
ans+=c;
cout<<c<<'\n';
cnt++;
}
if(cnt==V-1) break;
}
cout<<ans;
return 0;
}