10000 Merge pull request #410 from neppiness/2887 · REDICALED/basic-algo-lecture@cd338af · GitHub
[go: up one dir, main page]

Skip to content

Commit cd338af

Browse files
Merge pull request encrypted-def#410 from neppiness/2887
update: 0x1B 2887.cpp
2 parents 018d479 + e4a80e1 commit cd338af

File tree

1 file changed

+83
-4
lines changed

1 file changed

+83
-4
lines changed

0x1B/solutions/2887.cpp

Lines changed: 83 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,90 @@
1-
// Authored by : BaaaaaaaaaaarkingDog
1+
// Authored by : scsc3204
22
// Co-authored by : -
3-
// http://boj.kr/****************
3+
// http://boj.kr/3597912a5c77487e8a81bb93ae471450
44
#include <bits/stdc++.h>
55
using namespace std;
66

7-
int main(void){
7+
#define X first
8+
#define Y second
9+
10+
const int MX = 100'000;
11+
12+
int p[MX + 2];
13+
pair<int, int> x[MX + 2];
14+
pair<int, int> y[MX + 2];
15+
pair<int, int> z[MX + 2];
16+
17+
vector<tuple<int, int, int>> e; // e = {cost, u, v};
18+
19+
int find(int cur) {
20+
if(p[cur] < 0) return cur;
21+
return p[cur] = find(p[cur]);
22+
}
23+
24+
bool is_diff_group(int u, int v) {
25+
u = find(u); v = find(v);
26+
if(u == v) return 0;
27+
if(p[u] > p[v]) swap(u, v);
28+
p[u] += p[v];
29+
p[v] = u;
30+
return 1;
31+
}
32+
33+
int main() {
834
ios::sync_with_stdio(0);
935
cin.tie(0);
36+
37+
fill(p, p + MX + 2, -1);
38+
int n; cin >> n;
39+
for(int i = 0; i < n; i++) {
40+
int cx, cy, cz;
41+
cin >> cx >> cy >> cz;
42+
x[i] = {cx, i};
43+
y[i] = {cy, i};
44+
z[i] = {cz, i};
45+
}
1046

11-
}
47+
sort(x, x + n);
48+
sort(y, y + n);
49+
sort(z, z + n);
50+
51+
for(int i = 1; i < n; i++) {
52+
e.push_back({abs(x[i - 1].X - x[i].X), x[i - 1].Y, x[i].Y});
53+
e.push_back({abs(y[i - 1].X - y[i].X), y[i - 1].Y, y[i].Y});
54+
e.push_back({abs(z[i - 1].X - z[i].X), z[i - 1].Y, z[i].Y});
55+
}
56+
57+
sort(e.begin(), e.end());
58+
59+
int cnt = 0, sum = 0;
60+
for(auto [cost, u, v] : e) {
61+
if(!is_diff_group(u, v)) continue;
62+
sum += cost;
63+
cnt++;
64+
if(cnt == n - 1) break;
65+
}
66+
cout << sum;
67+
}
68+
/*
69+
모든 행성 간 간선을 계산하고 저장하면
70+
최악의 경우 약 50억 개의 간선 정보를 저장해야 합니다.
71+
따라서 꼭 필요한 간선 정보만 추려낼 논리가 필요합니다.
72+
73+
직관적으로 생각하면 새로운 행성을 MST에 추가할 때 굳이 가까운 행성 대신 더 멀리
74+
있는 행성을 택할 이유는 없어보입니다. 그렇기 때문에 x, y, z축 각각에 대해
75+
앞뒤에 인접한 행성에 대해서만 간선이 있다고 생각할 수 있습니다.
76+
77+
i번째 행성의 좌표 정보를 받아
78+
pair<int, int> x, y, z 배열에 저장합니다.
79+
이 배열은 좌표 값과 행성 번호를 기록합니다.
80+
81+
이 좌표 배열들을 정렬하면(47-49번째 줄)
82+
좌표의 차이가 적은 좌표 값들을 앞뒤 인덱스에 둘 수 있습니다.
83+
이를 활용해 좌표 값 간의 차이를 절대값으로 계산해 간선의 비용을 계산하고,
84+
간선이 잇는 두 행성의 번호를 간선 정보로 함께 저장합니다(51-55번째 줄).
85+
86+
이후 크루스칼 알고리즘을 따라
87+
간선 정보를 비용에 대해 오름차순으로 정렬하고,
88+
비용이 작은 간선부터 확인하며 MST를 구축합니다.
89+
이 과정에서 간선 가중치 총합의 최솟값을 계산하고 그 값을 답으로 출력합니다.
90+
*/

0 commit comments

Comments
 (0)
0