Cod sursa(job #1540188)

Utilizator mariusbsUnibuc Serban mariusbs Data 2 decembrie 2015 12:57:12
Problema Cele mai apropiate puncte din plan Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 2.21 kb
import java.io.*;
import java.util.*;

public class Point2D {
	int x, y;
	public static final Comparator<Point2D> X_THAN_Y_ORDER = new XThanYOrder();
	
	public Point2D(String text)
	{
		int space = text.indexOf(' ');
		x = Integer.parseInt(text.substring(0, space));
		y = Integer.parseInt(text.substring(space + 1));
	}
	
	public static Point2D[] read(String fileName)
	{
		Point2D points[] = null;
		try {
			BufferedReader br = new BufferedReader(new FileReader(fileName));
			points = new Point2D[Integer.parseInt(br.readLine())];
			for (int index = 0; index < points.length; ++index) {
				points[index] = new Point2D(br.readLine());
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return points;
	}
	
	public static long distance(Point2D a, Point2D b)
	{
		return square(b.x - a.x) + square(b.y - a.y);
	}
	
	public static long square(int number)
	{
		return (long)number * number;
	}
	private static class XThanYOrder implements Comparator<Point2D>
	{
		public int compare(Point2D a, Point2D b)
		{
			return (a.x != b.x) ? (a.x - b.x) : (a.y - b.y);
		}
	}
	
	public static double closest(Point2D[] points)
	{
		long solution = Long.MAX_VALUE, distance;
		Arrays.sort(points, 0, points.length, Point2D.X_THAN_Y_ORDER);
		for (int i = 0, end = points.length - 1; i < end; ++i) {
			for (int j = i + 1, end2 = (i + 8 > points.length ? points.length : i + 8); j < end2; ++j) {
				if (solution > (distance = distance(points[i], points[j]))) {
					solution = distance;
				}
			}
		}
		return Math.sqrt(solution);
	}
	
	public static void print(double number, String fileName)
	{
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter((new File(fileName)).getAbsoluteFile()));
			bw.write(String.format("%.6f", number));
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String toString()
	{
		return x + " " + y;
	}
	
	public static void print(Point2D points[])
	{
		for (int index = 0; index < points.length; ++index) {
			System.out.println(points[index]);
		}
	}
	
	public static void main(String[] args)
	{
		Point2D points[] = read("cmap.in");
		print(closest(points), "cmap.out");
	}
}