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

Jihun·2022년 2월 22일
0

BOJ

목록 보기
9/29
post-thumbnail

문제

도현이는 컴퓨터와 컴퓨터를 모두 연결하는 네트워크를 구축하려 한다. 하지만 아쉽게도 허브가 있지 않아 컴퓨터와 컴퓨터를 직접 연결하여야 한다. 그런데 모두가 자료를 공유하기 위해서는 모든 컴퓨터가 연결이 되어 있어야 한다. (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. 최초, 모든 간선을 가중치에 따라 오름차순으로 정렬
2. 가중치가 가장 낮은 간선부터 선택하면서 트리를 증가시킴
- 사이클이 존재하면 다음으로 가중치가 낮은 간선 선택
3. 총 노드 수 - 1 개의 간선이 선택될 때까지 2를 반복

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main_B1922 {
	static class Edge implements Comparable<Edge>{
		public int start,end,weight;

		public Edge(int start, int end, int weight) {
			this.start = start;
			this.end = end;
			this.weight = weight;
		}
		@Override
		public int compareTo(Edge o) {
			return this.weight-o.weight;
		}
	}
	
	static int n,m;
	static int[] parents;
	static Edge[]edgeList;
	
	public static int find(int x) {
		if (x==parents[x]) {
			return x;
		}
		return find(parents[x]);
	}
	public static boolean union(int x,int y) {
		int a=find(x);
		int b=find(y);
		
		if(a==b)return false;
		parents[b]=a;
		return true;
	}

	public static void main(String[] args) throws NumberFormatException, IOException {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			StringTokenizer st;
			n = Integer.parseInt(br.readLine());
			m = Integer.parseInt(br.readLine());
			parents = new int[n+1];
			for (int i=1;i<=n;i++) {
				parents[i] = i;
			}
			edgeList = new Edge[m];
			for(int i=0;i<m;i++) {
				st = new StringTokenizer(br.readLine());
				int from = Integer.parseInt(st.nextToken());
				int to = Integer.parseInt(st.nextToken());
				int weight = Integer.parseInt(st.nextToken());
				edgeList[i] = new Edge(from,to,weight);
			}			
			Arrays.sort(edgeList);
			int result=0,cnt=0;
			for(Edge edge:edgeList) {
				if(union(edge.start, edge.end)) {
					result+=edge.weight;
					if(++cnt==n-1)break;
				}
			}
			System.out.println(result);
	}

}
profile
slow and steady

0개의 댓글