Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 자바컴파일러
- HeapArea
- abstract
- pg_hba.conf
- la-piscine
- 바이트코드
- StackArea
- generics
- 상속관계
- 제네릭스
- classloader
- Compiler
- java
- SRP
- jdk
- RDD
- 42seoul
- JVM
- Operating System
- 운영체제
- LSP
- javac
- 도커네트워크
- 포함관계
- JIT
- 이노베이션아카데미
- 42서울
- 라피신
- 참조변수
- MethodArea
Archives
- Today
- Total
while(1) 작심삼일();
[백준 1197번] 최소 스패닝 트리 본문
http://www.acmicpc.net/problem/1197
1197번: 최소 스패닝 트리
첫째 줄에 정점의 개수 V(1 ≤ V ≤ 10,000)와 간선의 개수 E(1 ≤ E ≤ 100,000)가 주어진다. 다음 E개의 줄에는 각 간선에 대한 정보를 나타내는 세 정수 A, B, C가 주어진다. 이는 A번 정점과 B번 정점이
www.acmicpc.net
풀이)
크루스칼 알고리즘을 이용하기 위해 간선 가중치를 기준으로 오름차순으로 정렬해주었고 이후 union-find 알고리즘을 사용하여 싸이클을 확인한 후 같은 집합이 아니라면 추가해주는 방식으로 해결하였다.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int V, E, s, e, w, ans = 0;
int parent[10001];
pair<pair<int,int>, int> v[100001];
bool cmp(pair<pair<int,int>, int> v1, pair<pair<int,int>, int> v2){
return v1.second < v2.second;
}
int getParent(int x)
{
if(parent[x] == x)
return (x);
return getParent(parent[x]);
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> V >> E;
for(int i = 1; i <= V; i++)
parent[i] = i;
for(int i = 0; i < E; i++)
{
cin >> s >> e >> w;
v[i].first.first = s;
v[i].first.second = e;
v[i].second = w;
}
sort(v, v + E, cmp);
for(int i = 0; i < E; i++)
{
if (getParent(v[i].first.first) != getParent(v[i].first.second))
{
ans += v[i].second;
s = getParent(v[i].first.first);
e = getParent(v[i].first.second);
if (s < e)
parent[e] = s;
else
parent[s] = e;
}
}
cout << ans;
return (0);
}
제 코드는 절대 완벽하지 않습니다
더 좋은 풀이방법 혹은 코드에 관한 질문이 있으시면 언제든 댓글주세요!
'CS > baekjoon' 카테고리의 다른 글
[백준 1707번] 이분 그래프 (0) | 2021.04.03 |
---|---|
[백준 2056번] 작업 (0) | 2021.04.03 |
[백준 15683번] 감시 (0) | 2021.04.02 |
[백준 14503번] 로봇 청소기 (0) | 2021.03.15 |
[백준 14502번] 연구소 (0) | 2021.03.08 |
Comments