Cod sursa(job #1545631)

Utilizator PrickleOlimpiu Marinas Prickle Data 6 decembrie 2015 21:56:15
Problema Cele mai apropiate puncte din plan Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 1.69 kb
package cmap;

import java.util.*;
import java.io.*;

class Punct {
	public int x, y;

	Punct(int x, int y) {
		this.x = x;
		this.y = y;
	}

	long distanta(Punct B) {
		return (B.x - x) * (B.x - x) + (B.y - y) * (B.y - y);
	}
}

class PunctXComparator implements Comparator<Punct> {
	public int compare(Punct A, Punct B) {
		return B.x - A.x;
	}
}

class PunctYComparator implements Comparator<Punct> {
	public int compare(Punct A, Punct B) {
		return B.y - A.y;
	}
}

public class Cmap {
	public static void main(String arg[]) {
		File f = new File("cmap.in");
		if (f.exists())
			try {
				Scanner sc = new Scanner(f);
				int n = sc.nextInt();
				Punct[] puncte = new Punct[n];
				for (int i = 0; i < n; i++)
					puncte[i] = new Punct(sc.nextInt(), sc.nextInt());
				Arrays.sort(puncte, new PunctXComparator());
				double solutie = closest(puncte);

				try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("cmap.out")))) {
					writer.write(Double.toString(solutie));
				} catch (IOException e) {
					e.printStackTrace();
				}
				sc.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		else
			System.out.println("File not found!");
	}

	public static double closest(Punct[] puncte) {
		long solution = Long.MAX_VALUE;
		int frame = 4; // frame - 1 distances compared for each point
		for (int i = 0, end = puncte.length - 1; i < end; ++i) {
			for (int j = i + 1, end2 = (i + frame > puncte.length ? puncte.length : i + frame); j < end2; ++j) {
				if (solution > puncte[i].distanta(puncte[j])) {
					solution = puncte[i].distanta(puncte[j]);
				}
			}
		}
		return Math.sqrt(solution);
	}
}