Skip to content

Commit d62d7c7

Browse files
authored
[BOJ] 14621 나만 안 되는 연애 (G3)
1 parent 887c2b4 commit d62d7c7

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

박예진/9주차/260226.cpp

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// https://www.acmicpc.net/problem/14621
2+
#include <vector>
3+
#include <algorithm>
4+
#include <iostream>
5+
using namespace std;
6+
7+
int N, M, u, v, d, parent[1001];
8+
char gender[1001];
9+
10+
vector <pair <int, pair <int, int>>> graph;
11+
12+
int getParent(int x) {
13+
if (parent[x] == x) return x;
14+
return parent[x] = getParent(parent[x]);
15+
}
16+
17+
int main() {
18+
ios::sync_with_stdio(false);
19+
cin.tie(NULL); cout.tie(NULL);
20+
21+
cin >> N >> M;
22+
for (int i = 1; i <= N; i++) {
23+
cin >> gender[i];
24+
parent[i] = i;
25+
}
26+
for (int i = 0; i < M; i++) {
27+
cin >> u >> v >> d;
28+
if (gender[u] != gender[v]) {
29+
graph.push_back({ d, {u, v} });
30+
}
31+
}
32+
sort(graph.begin(), graph.end());
33+
34+
int sum = 0, cnt = 0;
35+
for (int i = 0; i < graph.size(); i++) {
36+
int cost = graph[i].first;
37+
int start = graph[i].second.first;
38+
int end = graph[i].second.second;
39+
40+
int a = getParent(start);
41+
int b = getParent(end);
42+
43+
if (a == b) continue;
44+
if (a > b) parent[a] = b;
45+
else parent[b] = a;
46+
47+
sum += cost;
48+
cnt++;
49+
if (cnt == N - 1) {
50+
cout << sum;
51+
break;
52+
}
53+
}
54+
int count = 0;
55+
for (int i = 1; i <= N; i++) {
56+
if (getParent(i) != getParent(1)) count++;
57+
}
58+
if (count > 0) cout << -1;
59+
}

0 commit comments

Comments
 (0)