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 |
Tags
- 정렬
- Team Fortress 2
- 구현
- 다익스트라
- VR
- 알고리즘
- XR Interaction Toolkit
- 시뮬레이션
- 수학
- 유니온 파인드
- 그리디 알고리즘
- 유니티
- ue5
- 트리
- 문자열
- 브루트포스
- DFS
- 우선순위 큐
- BFS
- 누적 합
- c++
- 스택
- Unreal Engine 5
- 재귀
- 그래프
- 다이나믹 프로그래밍
- 투 포인터
- 자료구조
- 백준
- 백트래킹
Archives
- Today
- Total
1일1알
백준 1922번 네트워크 연결 C++ 본문
기본적인 최소 스패닝 트리 문제인 것 같다. 유니온 파인드를 이용해서 풀었다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int n, m;
struct Computer {
int a;
int b;
int cost;
bool operator<(const Computer& other)const {
return cost < other.cost;
}
};
vector<int> parent;
vector<int> height;
int GetParnet(int n) {
if (n == parent[n])
return n;
return parent[n] = GetParnet(parent[n]);
}
void Merge(int u, int v) {
u = GetParnet(u);
v = GetParnet(v);
if (u == v) return;
if (height[u] > height[v])
::swap(u, v);
parent[u] = v;
if (height[u] == height[v])
height[v]++;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> m;
parent = vector<int>(n + 1);
height = vector<int>(n + 1, 1);
for (int i = 1; i <= n; i++) {
parent[i] = i;
}
int ans = 0;
vector<Computer> computers;
for (int i = 0; i < m; i++) {
int a, b, cost;
cin >> a >> b >> cost;
computers.push_back({ a,b,cost });
}
sort(computers.begin(), computers.end());
for (auto a : computers) {
if (GetParnet(a.a) == GetParnet(a.b)) continue;
Merge(a.a, a.b);
ans += a.cost;
}
cout << ans;
}
'알고리즘' 카테고리의 다른 글
백준 1261번 알고스팟 C++ (0) | 2022.08.11 |
---|---|
백준 3055번 탈출 C++ (0) | 2022.08.10 |
백준 1707번 이분 그래프 C++ (0) | 2022.08.08 |
백준 1976번 여행 가자 C++ (0) | 2022.08.07 |
백준 1039번 교환 C++ (0) | 2022.08.06 |