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 Ruby (judge verdict: Wrong Answer)

require 'matrix'
q = gets.to_i

class Segment
  attr_accessor :p1, :p2
  def initialize(p1, p2)
    @p1 = p1
    @p2 = p2
  end
end

def get_distance_sp(s, p)
  return (s.p1 - p).norm if (s.p2 - s.p1).inner_product(p - s.p1)
  return (s.p2 - p).norm if (s.p1 - s.p2).inner_product(p - s.p2)
  return (s.p2 - s.p1).cross_product(p - s.p1) / (s.p2 - s.p1).norm
end

def cross(p1, p2)
  return p1[0] * p2[1] - p1[1] * p2[0]
end

q.times do
  x0, y0, x1, y1, x2, y2, x3, y3 = gets.split.map &:to_i
  p0 = Vector[ x0, y0, 0 ]
  p1 = Vector[ x1, y1, 0 ]
  p2 = Vector[ x2, y2, 0 ]
  p3 = Vector[ x3, y3, 0 ]
  s1 = Segment.new(p0, p1)
  s2 = Segment.new(p2, p3)
  d = [ get_distance_sp(s1, s2.p1), get_distance_sp(s1, s2.p2), get_distance_sp(s2, s1.p1), get_distance_sp(s2, s1.p2) ].min
  d = 0 if cross(p1 - p0, p2 - p0) * cross(p1 - p0, p3 - p0) < 0 && cross(p3 - p2, p0 - p2) * cross(p3 - p2, p1 - p2) < 0
  puts "%.8f" % d
end