X Tutup
import java.util.*; class Edge implements Comparable { private int distance; private int nodeA; private int nodeB; public Edge(int distance, int nodeA, int nodeB) { this.distance = distance; this.nodeA = nodeA; this.nodeB = nodeB; } public int getDistance() { return this.distance; } public int getNodeA() { return this.nodeA; } public int getNodeB() { return this.nodeB; } // 거리(비용)가 짧은 것이 높은 우선순위를 가지도록 설정 @Override public int compareTo(Edge other) { if (this.distance < other.distance) { return -1; } return 1; } } class Position implements Comparable { private int x; private int y; public Position(int x, int y) { this.x = x; this.y = y; } public int getX() { return this.x; } public int getY() { return this.y; } // X축, Y축 순서대로 정렬 @Override public int compareTo(Position other) { if (this.x == other.x) { return Integer.compare(this.y, other.y); } return Integer.compare(this.x, other.x); } } public class Main { // 노드의 개수 public static int n; public static int[] parent = new int[100001]; // 부모 테이블 초기화 // 모든 간선을 담을 리스트와, 최종 비용을 담을 변수 public static ArrayList edges = new ArrayList<>(); public static int result = 0; // 특정 원소가 속한 집합을 찾기 public static int findParent(int x) { // 루트 노드가 아니라면, 루트 노드를 찾을 때까지 재귀적으로 호출 if (x == parent[x]) return x; return parent[x] = findParent(parent[x]); } // 두 원소가 속한 집합을 합치기 public static void unionParent(int a, int b) { a = findParent(a); b = findParent(b); if (a < b) parent[b] = a; else parent[a] = b; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); // 부모 테이블상에서, 부모를 자기 자신으로 초기화 for (int i = 1; i <= n; i++) { parent[i] = i; } ArrayList x = new ArrayList(); ArrayList y = new ArrayList(); ArrayList z = new ArrayList(); // 모든 노드에 대한 좌표 값 입력받기 for (int i = 1; i <= n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); x.add(new Position(a, i)); y.add(new Position(b, i)); z.add(new Position(c, i)); } Collections.sort(x); Collections.sort(y); Collections.sort(z); // 인접한 노드들로부터 간선 정보를 추출하여 처리 for (int i = 0; i < n - 1; i++) { edges.add(new Edge(x.get(i + 1).getX() - x.get(i).getX(), x.get(i).getY(), x.get(i + 1).getY())); edges.add(new Edge(y.get(i + 1).getX() - y.get(i).getX(), y.get(i).getY(), y.get(i + 1).getY())); edges.add(new Edge(z.get(i + 1).getX() - z.get(i).getX(), z.get(i).getY(), z.get(i + 1).getY())); } // 간선을 비용순으로 정렬 Collections.sort(edges); // 간선을 하나씩 확인하며 for (int i = 0; i < edges.size(); i++) { int cost = edges.get(i).getDistance(); int a = edges.get(i).getNodeA(); int b = edges.get(i).getNodeB(); // 사이클이 발생하지 않는 경우에만 집합에 포함 if (findParent(a) != findParent(b)) { unionParent(a, b); result += cost; } } System.out.println(result); } }
X Tutup