Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

코드와이

[BAEKJOON] 4386. 별자리 만들기 본문

acmicpc

[BAEKJOON] 4386. 별자리 만들기

코드와이 2021. 10. 10. 17:02

Kruskal

 

문제링크

https://www.acmicpc.net/problem/4386

 

4386번: 별자리 만들기

도현이는 우주의 신이다. 이제 도현이는 아무렇게나 널브러져 있는 n개의 별들을 이어서 별자리를 하나 만들 것이다. 별자리의 조건은 다음과 같다. 별자리를 이루는 선은 서로 다른 두 별을 일

www.acmicpc.net

 

package acmicpc.Gold4;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class 별자리_만들기 {

	static int n, parent[];
	static List<Node> list;
	static class Node{
		double x, y;

		public Node(double x, double y) {
			super();
			this.x = x;
			this.y = y;
		}

	}
	static class Dist implements Comparable<Dist>{
		int from, to;
		double dist;

		public Dist(int from, int to, double dist) {
			super();
			this.from = from;
			this.to = to;
			this.dist = dist;
		}
		
		@Override
		public int compareTo(Dist o) {
			if(dist > o.dist) return 1;
			else return -1;
		}

		@Override
		public String toString() {
			return "Dist [from=" + from + ", to=" + to + ", dist=" + dist + "]";
		}
		
		
	}
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		
		n = Integer.parseInt(br.readLine());
		
		list = new ArrayList<>();

		for(int i = 0 ; i < n ; i++) {
			
			st = new StringTokenizer(br.readLine());
					
			double x = Double.parseDouble(st.nextToken());
			double y = Double.parseDouble(st.nextToken());
		
			list.add(new Node(x, y));
		
		}
		
		PriorityQueue<Dist> pq = new PriorityQueue<>();
		
		for(int i = 0 ; i < n ; i++) {
			for(int j = i + 1 ; j < n ; j++) {
				
				Node from = list.get(i);
				Node to = list.get(j);
				
				pq.add(new Dist(i, j, Math.sqrt(Math.pow((from.x - to.x), 2) + Math.pow((from.y - to.y), 2))));
				
			}
		}

		double ans = 0;
		parent = new int[n];
		parent();
		
		while(!pq.isEmpty()) {
			
			Dist d = pq.poll();
			
			if(findSet(d.from) != findSet(d.to)) {
				union(d.from, d.to);
				ans += d.dist;
			}
			
		}
			
		
		System.out.printf("%.2f", ans);
	}
	
	public static void parent() {
		for(int i = 0 ; i < n ; i++) {
			parent[i] = i;
		}
	}
	
	public static int findSet(int x) {
		if(parent[x] == x) return x;
		
		return parent[x] = findSet(parent[x]);
	}
	
	public static void union(int a, int b) {
		
		int aSet = findSet(a);
		int bSet = findSet(b);
		
		if(aSet == bSet) return;
		
		parent[bSet] = aSet;
		
	}
}

'acmicpc' 카테고리의 다른 글

[BAEKJOON] 17406. 배열 돌리기4  (0) 2021.10.16
[BAEKJOON] 10775. 공항  (0) 2021.10.10
[BAEKJOON] 1939. 중량 제한  (0) 2021.10.09
[BAEKJOON] 17825. 주사위 윷놀이  (0) 2021.09.26
[BAEKJOON] 17822. 원판 돌리기  (0) 2021.09.26