Cod sursa(job #1540195)

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

class cmap {
	int x, y;
	public static final Comparator<cmap> X_THAN_Y_ORDER = new XThanYOrder();
	
	public cmap(String text)
	{
		int space = text.indexOf(' ');
		x = Integer.parseInt(text.substring(0, space));
		y = Integer.parseInt(text.substring(space + 1));
	}
	
	public static cmap[] read(String fileName)
	{
		cmap points[] = null;
		try {
			BufferedReader br = new BufferedReader(new FileReader(fileName));
			points = new cmap[Integer.parseInt(br.readLine())];
			for (int index = 0; index < points.length; ++index) {
				points[index] = new cmap(br.readLine());
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return points;
	}
	
	public static long distance(cmap a, cmap 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<cmap>
	{
		public int compare(cmap a, cmap b)
		{
			return (a.x != b.x) ? (a.x - b.x) : (a.y - b.y);
		}
	}
	
	public static double closest(cmap[] points)
	{
		long solution = Long.MAX_VALUE, distance;
		Arrays.sort(points, 0, points.length, cmap.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(cmap points[])
	{
		for (int index = 0; index < points.length; ++index) {
			System.out.println(points[index]);
		}
	}
	
	public static void main(String[] args)
	{
		cmap points[] = cmap.read("cmap.in");
		cmap.print(cmap.closest(points), "cmap.out");
	}
}