[인터돌™] 공부 해보자!! 열심히~~~

반응형

문제 : https://www.acmicpc.net/problem/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는 같을 수도 있다.

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

 

예제 입력, 출력

  예제 입력 예제 출력
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
23

 

사용 알고리즘

MST (최소신장트리)

 

코드 (자바)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

// 네트워크 연결 : https://www.acmicpc.net/problem/1922
// MST (최소신장 트리)

/*

샘플 입력

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

 */

public class Main {
	static int[] parent ;		// 부모 노드 정보를 저장할 배열
	
	// root 노드를 반환하는 메소드
	static int find (int x) {
		
		if (x == parent[x]) {
			return x ; 
		}
		else {
			return parent[x] = find(parent[x]);
		}
	}
	
	// 두개의 집합을 합치는 메소드. union 을 하는 경우 true 를 반환
	static boolean union (int x, int y) {
		int parentX = find(x);
		int parentY = find(y);
		
		if (parentX != parentY) {
//			parent[parentY] = parentX;
			parent[parentY] = parent[parentX];	// 위에 줄이나 이거나 둘다 같을 듯?
			return true;
		}
		
		return false;
	}
	
	
	
	public static void main(String[] args) throws Exception {
		
		// 필요 변수 선언
		int N = 0;	// 컴퓨터의 수
		int M = 0;	// 연결할 수 있는 선의 수
		int sum = 0;	// 연결할 수 있는 최소 비용의 합
		
		// 입력값 처리
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		N = Integer.parseInt(st.nextToken());
		st =new StringTokenizer(br.readLine());
		M = Integer.parseInt(st.nextToken());
		
		// 거리(비용) 오름차순으로 정렬하기 위한 우선순위 큐 선언
		PriorityQueue<Info> pq = new PriorityQueue<Info>(new Comparator<Info>() {
			@Override
			public int compare(Info o1, Info o2) {
				// TODO Auto-generated method stub
				return o1.distance - o2.distance;
			}
			
		});
		
		for (int i=1; i<=M; i++) {
			st =new StringTokenizer(br.readLine());
			int tempFrom = Integer.parseInt(st.nextToken());
			int tempTo = Integer.parseInt(st.nextToken());
			int tempDistance = Integer.parseInt(st.nextToken());
			pq.add(new Info(tempFrom, tempTo, tempDistance));
			
		}
		

		// pq 가 잘 작동하는지 확인
//		for (int i=1; i<=M; i++) {
//			Info info = pq.poll();
//			System.out.println(info.from + " " + info.to + " " + info.distance);
//		}
		
		
		// parent 배열 초기화
		parent = new int[N+1];	// 컴퓨터의 개수보다 한개 더 크게 배열 생성 (1 베이스로 할꺼기 때문)
		for (int i=1 ; i<=N ; i++) {
			parent[i] = i;		// parent 배열의 값을 인덱스와 동일하게 초기화
		}
		
//		System.out.println(Arrays.toString(parent));	// parent 배열에 들어있는 값 확인

		// 메인 로직 시작
		// pq 가 빌 때 까지 반복하고, union 을 하는 경우 비용을 결과값에 합산
		while (!pq.isEmpty()) {
			Info info = pq.poll();
			if (union(info.from, info.to)) {
				sum += info.distance;
			}
			
		}
		
		System.out.println(sum);	// 최종 합계 출력
		
	}
	
	// 시작점, 종료점, 거리(비용) 을 저장하기 위한 클래스
	static class Info {
		int from;
		int to;
		int distance;
		
		Info(int from, int to, int distance){
			this.from = from;
			this.to = to;
			this.distance = distance;
		}
	}
}

 

 

 

 

 

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band