yukicoder No. 168: ものさし (Union-Find木)

解法

任意の2点間の距離(最低限必要になるものさしの長さ)を求めておく。それらをソートし、距離の小さい順に取り出していく。取り出した辺の始点と終点を結び、Union-Find木で結合しておく。点1と点N-1が同じ木になるまで辺を取り出し続け、同じ木になった時の辺が、最大の辺である。

コード

import java.io.IOException;
import java.util.PriorityQueue;

public class Main {
	public static void main(String[] args) {
		int N = nextInt();
		int[] x = new int[N];
		int[] y = new int[N];
		for (int i = 0; i < N; i++) {
			x[i] = nextInt();
			y[i] = nextInt();
		}

		PriorityQueue<Edge> priorityQueue = new PriorityQueue<>();
		UnionFind uFind = new UnionFind(N);

		for (int i = 0; i < N; i++) {
			for (int j = 0; j < i; j++) {
				long dx = x[i] - x[j];
				long dy = y[i] - y[j];
				long distSq = dx * dx + dy * dy;
				long d = (long) Math.sqrt(distSq);
				while (distSq > d * d) {
					d++;
				}

				d = (d + 9) / 10 * 10;
				priorityQueue.add(new Edge(i, j, (int) d));
			}
		}

		int max = 0;
		while (!uFind.isSame(0, N - 1)) {
			Edge edge = priorityQueue.poll();
			if (!uFind.isSame(edge.from, edge.to)) {
				uFind.unite(edge.from, edge.to);
				max = Math.max(max, edge.weight);
			}
		}
		System.out.println(max);

	}

	static int nextInt() {
		int c;
		try {
			c = System.in.read();
			while (c != '-' && (c < '0' || c > '9'))
				c = System.in.read();
			if (c == '-')
				return -nextInt();
			int res = 0;
			while (c >= '0' && c <= '9') {
				res = res * 10 + c - '0';
				c = System.in.read();
			}
			return res;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}
}

class UnionFind {
	int[] parts;

	UnionFind(int n) {
		parts = new int[n];
		for (int i = 0; i < n; i++)
			parts[i] = i;
	}

	public int find(int x) {
		if (parts[x] == x)
			return x;
		return parts[x] = find(parts[x]);
	}

	public Boolean isSame(int x, int y) {
		return find(x) == find(y);
	}

	public void unite(int x, int y) {
		if (find(x) == find(y))
			return;
		parts[find(x)] = find(y);
	}
}

class Edge implements Comparable<Edge> {
	int weight;
	int from, to;

	Edge(int f, int t, int w) {
		this.weight = w;
		this.from = f;
		this.to = t;
	}

	@Override
	public int compareTo(Edge edge) {
		// 昇順
		return this.weight - edge.weight;
	}
}