Skip to content

Commit

Permalink
baekjoon/gold4/q1922_network_connection(네트워크연결)
Browse files Browse the repository at this point in the history
  • Loading branch information
bong6981 committed Jan 16, 2022
1 parent 92a19f0 commit 3091dd1
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
66 changes: 66 additions & 0 deletions baekjoon/java/src/gold4/Q1922_ConnectionOfNetwork.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package gold4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

// https://www.acmicpc.net/problem/1922
public class Q1922_ConnectionOfNetwork {
private static int[] parents;

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
parents = new int[n + 1];
for (int i = 1; i <= n; i++) {
parents[i] = i;
}
List<List<Integer>> connections = new ArrayList<>();
int m = Integer.parseInt(br.readLine());
for (int i = 0; i < m; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
connections.add(Stream.of(c, a, b).collect(Collectors.toList()));
}

connections.sort(Comparator.comparingInt(conn -> conn.get(0)));
int total = 0;
for (List<Integer> connection : connections) {
int x = connection.get(1);
int y = connection.get(2);
if (findParent(x) != findParent(y)) {
union(x, y);
total += connection.get(0);
}
}
System.out.println(total);
}

private static int findParent(int x) {
if (parents[x] != x) {
parents[x] = findParent(parents[x]);
}
return parents[x];
}

private static void union(int x, int y) {
x = findParent(x);
y = findParent(y);
if (x == y) {
return;
}
if (x < y) {
parents[y] = x;
return;
}
parents[x] = y;
}
}
35 changes: 35 additions & 0 deletions baekjoon/python/gold4/q1922_network_connection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# https://www.acmicpc.net/problem/1922
def solution():
global parent
n = int(input())
parent = [i for i in range(n+1)]
connections = []
m = int(input())
for _ in range(m):
a, b, c = map(int, input().split())
connections.append((c, a, b))
connections.sort()
total = 0
for conn in connections:
c, a, b = conn
if find_p(a) != find_p(b):
union(a, b)
total += c
return total

def find_p(x):
if parent[x] != x:
parent[x] = find_p(parent[x])
return parent[x]

def union(x, y):
x = find_p(x)
y = find_p(y)
if x == y :
return
if x < y :
parent[y] = x
else:
parent[x] = y

print(solution())

0 comments on commit 3091dd1

Please sign in to comment.