본문 바로가기
공부 정리/백준

[백준] 자바 1922 네트워크 연결

by 경적필패. 2022. 4. 26.
반응형

문제

도현이는 컴퓨터와 컴퓨터를 모두 연결하는 네트워크를 구축하려 한다. 하지만 아쉽게도 허브가 있지 않아 컴퓨터와 컴퓨터를 직접 연결하여야 한다. 그런데 모두가 자료를 공유하기 위해서는 모든 컴퓨터가 연결이 되어 있어야 한다. (a와 b가 연결이 되어 있다는 말은 a에서 b로의 경로가 존재한다는 것을 의미한다. a에서 b를 연결하는 선이 있고, b와 c를 연결하는 선이 있으면 a와 c는 연결이 되어 있다.)

그런데 이왕이면 컴퓨터를 연결하는 비용을 최소로 하여야 컴퓨터를 연결하는 비용 외에 다른 곳에 돈을 더 쓸 수 있을 것이다. 이제 각 컴퓨터를 연결하는데 필요한 비용이 주어졌을 때 모든 컴퓨터를 연결하는데 필요한 최소비용을 출력하라. 모든 컴퓨터를 연결할 수 없는 경우는 없다.

입력

첫째 줄에 컴퓨터의 수 N (1 ≤ N ≤ 1000)가 주어진다.

둘째 줄에는 연결할 수 있는 선의 수 M (1 ≤ M ≤ 100,000)가 주어진다.

셋째 줄부터 M+2번째 줄까지 총 M개의 줄에 각 컴퓨터를 연결하는데 드는 비용이 주어진다. 이 비용의 정보는 세 개의 정수로 주어지는데, 만약에 a b c 가 주어져 있다고 하면 a컴퓨터와 b컴퓨터를 연결하는데 비용이 c (1 ≤ c ≤ 10,000) 만큼 든다는 것을 의미한다. a와 b는 같을 수도 있다.

출력

모든 컴퓨터를 연결하는데 필요한 최소비용을 첫째 줄에 출력한다.


테스트 케이스

 

입력 1

6
9
1 2 5
1 3 4
2 3 2
2 4 7
3 4 6
3 5 11
4 5 3
4 6 8
5 6 8

출력 1

23

 

입력 2

5
3
1 2 3
2 3 4
3 4 5

출력 2

12

 

입력 3

10
5
1 2 3
2 3 4
3 4 5
4 5 6
6 7 8

출력 3

26


접근

무방향 그래프이고, 모든 점(컴퓨터)를 연결하는 최소비용을 구해야 하기 때문에 크루스칼 알고리즘을 이용하여 해결하였습니다.

크루스칼 알고리즘대로, 간선을 가중치순으로 쫙 정렬한 뒤에, union-find 알고리즘을 이용하여 사이클이 생기는걸 방지하면서 가중치를 더해줬습니다.

 


코드

import java.io.*;
import java.util.*;
class ComputerLine implements Comparable<ComputerLine>{
	int from;
	int to;
	int weight;
	
	public ComputerLine(int from, int to, int weight) {
		this.from = from;
		this.to = to;
		this.weight = weight;
	}
	@Override
	public int compareTo(ComputerLine o) {
		// TODO Auto-generated method stub
		return this.weight - o.weight;
	}
	
}
public class Main {

	static int N,M,parent[];
	static ComputerLine[] computer;
	public static void makeSet() {
		parent = new int[N];
		for(int i=1; i<=N; i++) {
			parent[i-1] = i;
		}
	}
	public static int findParent(int a) {
		if(parent[a-1] == a) return a;
		return parent[a-1] = findParent(parent[a-1]);
	}
	
	public static boolean union(int a, int b) {
		int aRoot = findParent(a);
		int bRoot = findParent(b);
		
		if(aRoot == bRoot) {
			return false;
		}
		
		parent[bRoot-1] = aRoot;
		return true;
	}
	public static void main(String[] args) throws Exception {
	    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	    
	    N = Integer.parseInt(br.readLine());
	    M = Integer.parseInt(br.readLine());
	    int result = 0;
	    makeSet();
	    computer = new ComputerLine[M];
	    for(int i=0; i<M; i++) {
	    	StringTokenizer st = new StringTokenizer(br.readLine());
	    	int from = Integer.parseInt(st.nextToken());
	    	int to = Integer.parseInt(st.nextToken());
	    	int weight = Integer.parseInt(st.nextToken());
	    	computer[i] = new ComputerLine(from,to,weight);
	    }
	    Arrays.sort(computer);
	    
	    for(int i=0; i<M; i++) {
	    	if(union(computer[i].from, computer[i].to)) {
	    		result += computer[i].weight;
	    	}
	    }
	    bw.write(String.valueOf(result));
	    br.close();
	    bw.flush();
	    bw.close();
	    }
	}

주의

union-find, 크루스칼

 

반응형

댓글