BOJ 1922

2020-10-16

위 문제는 백준 사이트의 알고리즘 1922 문제에 관한 설명입니다.


문제

도현이는 컴퓨터와 컴퓨터를 모두 연결하는 네트워크를 구축하려 한다.

하지만 아쉽게도 허브가 있지 않아 컴퓨터와 컴퓨터를 직접 연결하여야 한다.

그런데 모두가 자료를 공유하기 위해서는 모든 컴퓨터가 연결이 되어 있어야 한다.

(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는 같을 수도 있다.

출력

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

소스코드


package day1016;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {

	public static int[] parent;
	public static ArrayList<Edge> edgeList;
	public static int answer = 0;

	public static int find(int x) {
		if (parent[x] == x)
			return x;
		else
			return parent[x] = find(parent[x]);
	}

	public static boolean union(int x, int y) {
		x = find(x);
		y = find(y);
		if (x != y) {
			parent[y] = x;
			return true;
		} else
			return false;
	}

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int E = scanner.nextInt();
		int V = scanner.nextInt();
		edgeList = new ArrayList<Edge>();
		for (int i = 0; i < V; i++) {
			int from = scanner.nextInt();
			int to = scanner.nextInt();
			int cost = scanner.nextInt();
			edgeList.add(new Edge(from, to, cost));
		}
		Collections.sort(edgeList);
		parent = new int[E + 1];
		for (int i = 1; i <= E; i++) {
			parent[i] = i;
		}
		for (int i = 0; i < V; i++) {
			Edge edge = edgeList.get(i);
			if (union(edge.from, edge.to)) {
				answer += edge.cost;
			}
		}
		System.out.println(answer);
		scanner.close();
	}
}

class Edge implements Comparable<Edge> {
	int from;
	int to;
	int cost;
	Edge(int v1, int v2, int cost) {
		this.from = v1;
		this.to = v2;
		this.cost = cost;
	}
	@Override
	public int compareTo(Edge o) {
		if (this.cost < o.cost)
			return -1;
		else if (this.cost == o.cost)
			return 0;
		else
			return 1;
	}
}


이번 문제는 크루스칼 알고리즘으로 풀었습니다.

이전 크루스칼 활용했던 문제 풀이

		//입력부
		Scanner scanner = new Scanner(System.in);
		int E = scanner.nextInt();
		int V = scanner.nextInt();
		edgeList = new ArrayList<Edge>();
		for (int i = 0; i < V; i++) {
			int from = scanner.nextInt();
			int to = scanner.nextInt();
			int cost = scanner.nextInt();
			edgeList.add(new Edge(from, to, cost));
		}

입력부에서는 크루스칼 알고리즘을 활용하기 위해 시작점, 끝점, 가중치로 간선들의 정보를 list로 만들어 데이터를 담아줍니다.

		//정렬 1.
		Collections.sort(edgeList);

		...

class Edge implements Comparable<Edge> {
	int from;
	int to;
	int cost;
	Edge(int v1, int v2, int cost) {
		this.from = v1;
		this.to = v2;
		this.cost = cost;
	}
	@Override
	public int compareTo(Edge o) {
		if (this.cost < o.cost)
			return -1;
		else if (this.cost == o.cost)
			return 0;
		else
			return 1;
	}
}

간선의 가중치를 오름차순으로 정렬하기 위해 오름차순 정렬을 합니다.

Collections의 sort기능을 활용하기 위해 Comparable을 implements 해줍니다.

그럼 클래스 내부에서 compareTo를 오버라이드 시켜서 기준을 만들어줍시다.


	public static int find(int x) {
		if (parent[x] == x)
			return x;
		else
			return parent[x] = find(parent[x]);
	}

	public static boolean union(int x, int y) {
		x = find(x);
		y = find(y);
		if (x != y) {
			parent[y] = x;
			return true;
		} else
			return false;
	}

	//... 생략

		parent = new int[E + 1];
		for (int i = 1; i <= E; i++) {
			parent[i] = i;
		}
		for (int i = 0; i < V; i++) {
			Edge edge = edgeList.get(i);
			if (union(edge.from, edge.to)) {
				answer += edge.cost;
			}
		}
		System.out.println(answer);
		scanner.close();

find함수와 union함수를 사용한 모습입니다.

union함수에서 find함수를 통해 xy의 부모값이 서로 다르다면 연결시킨 후 true를 리턴하고,

다르다면 연결시키지 않은 채 false를 리턴합니다.

만약 true값이 if문에 걸린다면 연결되었으니 가중치값을 결과 값에 추가합니다.

네트워크 연결