티스토리 뷰
https://www.acmicpc.net/problem/13418
13418번: 학교 탐방하기
입력 데이터는 표준 입력을 사용한다. 입력은 1개의 테스트 데이터로 구성된다. 입력의 첫 번째 줄에는 건물의 개수 N(1 ≤ N ≤ 1,000)과 도로의 개수 M(1 ≤ M ≤ N(N-1)/2) 이 주어진다. 입력의 두 번
www.acmicpc.net
내림차순 정렬후 크루스칼 알고리즘.
오름차순 정렬후 크루스칼 알고리즘.
총 두번 돌려주면 되는 문제.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
using namespace std; | |
int N, M; | |
vector<pair<int,pair<int,int>>> edges; | |
int parent[1010]; | |
int GetParent(int node) { | |
if(node == parent[node]) return node; | |
return parent[node] = GetParent(parent[node]); | |
} | |
bool IsParentSame(int node1, int node2) { | |
return GetParent(node1) == GetParent(node2); | |
} | |
void Union(int node1, int node2) { | |
node1 = GetParent(node1); | |
node2 = GetParent(node2); | |
parent[max(node1,node2)] = min(node1, node2); | |
} | |
int Kruskal() { | |
int sum = 0, cnt = 0; | |
for(auto x : edges) { | |
int cost = x.first; | |
int node1 = x.second.first, node2 = x.second.second; | |
if (!IsParentSame(node1, node2)) { | |
Union(node1, node2); | |
if(cost == 1) | |
sum += cost; | |
cnt++; | |
} | |
if(cnt == N-1) break; | |
} | |
return sum*sum; | |
} | |
void Init() { | |
for(int i = 0; i <= N; i++) { | |
parent[i] = i; | |
} | |
} | |
int main() { | |
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); | |
cin >> N >> M; | |
N++; | |
for(int i = 0; i < M+1; i++) { | |
int a, b, c; cin >> a >> b >> c; | |
c = c == 0 ? 1 : 0; | |
edges.push_back({c, {a, b}}); | |
} | |
Init(); | |
// 내림 차순 | |
sort(edges.begin(), edges.end(), greater<>()); | |
int ans1 = Kruskal(); | |
Init(); | |
// 오름 차순 | |
sort(edges.begin(), edges.end(), less<>()); | |
int ans2 = Kruskal(); | |
cout << ans1-ans2; | |
} |
'PS' 카테고리의 다른 글
백준 10423. 전기가 부족해 (0) | 2023.04.11 |
---|---|
백준 1477. 휴게소 세우기 (0) | 2023.04.10 |
백준 2800. 괄호 제거 (0) | 2023.04.03 |
백준 16938. 캠프 준비 (0) | 2023.04.01 |
백준 1484. 다이어트 (0) | 2023.03.31 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- dfs
- C
- Spring
- permutation
- Python
- floyd warshall
- 재귀
- priority queue
- back tracking
- graph
- db
- CSS
- recursion
- two pointer
- Tree
- C++
- Implementation
- Unity
- Dijkstra
- Kruskal
- greedy
- DP
- binary search
- BFS
- 조합
- MVC
- 자료구조
- 이분탐색
- Brute Force
- Stack
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함