티스토리 뷰
https://www.acmicpc.net/problem/1197
집합 연산을 나타내는 유니온 파인드를 이용한 크루스칼 알고리즘으로 최소 스패닝 트리(Minimum Spanning Tree)를 구성한다. 그래프의 모든 간선을 저장하고 정렬한 다음 가중치가 작은것 부터 뽑는다. 간선의 양 끝 정점이 같은 집합인지 파인드 연산을 통해 확인하고 다른 집합이면 유니온 연산을 통해 같은 집합으로 합쳐주고 간선을 최소 스패닝 트리에 추가한다. 이 과정을 모든 정점이 같은 집합에 포함될 때 까지 반복하면 N-1개의 간선으로 구성된 최소 스패닝 트리가 완성된다.
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 | #include <cstdio> #include <vector> #include <algorithm> using namespace std; struct Edge { int start,end,cost; bool operator < (const Edge &other) const { return cost<other.cost; } }; int p[10001]; int Find(int x) { return x==p[x]?x:p[x]=Find(p[x]); } void Union(int x,int y) { p[Find(x)]=Find(y); } int main() { int n,m,ans=0; scanf("%d %d",&n,&m); for(int i=1;i<=n;i++) p[i]=i; vector<Edge> a(m); for(int i=0;i<m;i++) scanf("%d %d %d",&a[i].start,&a[i].end,&a[i].cost); sort(a.begin(),a.end()); for(int i=0;i<m;i++) { Edge e=a[i]; int x=Find(e.start),y=Find(e.end); if(x!=y) Union(e.start,e.end),ans+=e.cost; } printf("%d\n",ans); return 0; } | cs |
'Algorithm > BOJ' 카테고리의 다른 글
1956 운동 (0) | 2018.02.06 |
---|---|
1507 궁금한 민호 (0) | 2018.02.06 |
2357 최소값과 최대값 (0) | 2018.02.06 |
11780 플로이드 2 (0) | 2018.02.06 |
2042 구간 합 구하기 (0) | 2018.02.06 |