문제
- 문제 링크
BOJ 16302 - Jurassic Jigsaw
mst 역추적
TL : $1$ sec, ML : $512$ MB
$1 ≤ N ≤ 1,000$ $1 ≤ k ≤ 10$
알고리즘 분류
- 그래프 이론(graphs)
- 최소 스패닝 트리(mst)
풀이
그냥 기본 mst 문제다.
임의의 문자열 쌍마다 서로 다른 문자 수 만큼 가중치를 메긴 뒤 mst를 돌려주면 된다.
전체 코드
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 | #include<bits/stdc++.h> using namespace std; struct E { int x, y, w; bool operator<(E& e) { return w < e.w; } }; vector <E> Eg, an; int n, k, i, P[1001]; int f(int p) { return P[p] = P[p] == p ? p : f(P[p]); } int main() { ios_base::sync_with_stdio(0); cin.tie(0); iota(P, P + 1001, 0); cin >> n >> k; for (vector <string> V(n); n--; i++) { cin >> V[i]; for (int j{}, c{}; j < i; c = 0, j++) { for (int l{}; l < k; l++) c += V[j][l] != V[i][l]; Eg.push_back({ j, i, c }); } } i = 0; sort(Eg.begin(), Eg.end()); for (auto& [x, y, w] : Eg) { n = f(x), k = f(y); if (n ^ k) { an.push_back({ x, y, 0 }); i += w; n > k ? P[n] = k : P[k] = n; } } cout << i << '\n'; for (auto& [x, y, w] : an) cout << x << ' ' << y << '\n'; } | cs |
comment
끝
'Problem Solving > Baekjoon Online Judge (Gold)' 카테고리의 다른 글
백준 27896 - 특별한 서빙 (C++) (1) | 2023.04.25 |
---|---|
백준 23354 - 군탈체포조 (C++) (0) | 2023.04.25 |
백준 1823 - 수확 (C++) (0) | 2023.04.24 |
백준 14948 - 군대 탈출하기 (C++) (0) | 2023.04.23 |
백준 13502 - 단어퍼즐 2 (C++) (0) | 2023.04.23 |