Problem:
Distance

For given two segments s1 and s2, print the distance between them.

s1 is formed by end points p0 and p1, and
s2 is formed by end points p2 and p3.

Input

The entire input looks like:

q (the number of queries)
1st query
2nd query
...
qth query

Each query consists of integer coordinates of end points of s1 and s2 in the following format:

xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3

Output

For each query, print the distance. The output values should be in a decimal fraction with an error less than 0.00000001.

Constraints

1 ≤ q ≤ 1000

-10000 ≤ xpi, ypi ≤ 10000

p0 ≠ p1 and
p2 ≠ p3.

Sample Input

3
0 0 1 0 0 1 1 1
0 0 1 0 2 1 1 2
-1 0 1 0 0 1 0 -1

Sample Output

1.0000000000
1.4142135624
0.0000000000

Solution in JAVA (judge verdict: Accepted)



import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		int n = Integer.parseInt(br.readLine());


		for(int i = 0; i < n; i++){
			String[] tmpArray = br.readLine().split(" ");

			Point2D[] points = new Point2D[4];

			for(int j = 0; j < 4; j++){
				int x = Integer.parseInt(tmpArray[j*2]);
				int y = Integer.parseInt(tmpArray[j*2 + 1]);

				points[j] = new Point2D.Double(x, y);
			}

			Line2D[] lines = new Line2D[2];
			for(int j = 0; j < 2; j++){
				lines[j] = new Line2D.Double(points[j*2], points[j*2 + 1]);
			}

			double result = distance(lines[0], lines[1]);

			System.out.printf("%.8f\n", result);
		}
	}

	static double distance(Line2D l1, Line2D l2){
		if(l1.intersectsLine(l2)){
			return 0;
		}

		else {
			return Math.min(Math.min(l2.ptSegDist(l1.getP1()), l2.ptSegDist(l1.getP2())), Math.min(l1.ptSegDist(l2.getP1()), l1.ptSegDist(l2.getP2())));
		}
	}

}