Problem:
Cross Point

For given two segments s1 and s2, print the coordinate of the cross point of 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 coordinate of the cross point. 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.

The given segments have a cross point and are not in parallel.

Sample Input

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

Sample Output

1.0000000000 0.0000000000
0.5000000000 0.5000000000
0.5000000000 0.5000000000

Solution in Haskell (judge verdict: Accepted)

import Control.Applicative ((<$>))
import Control.Monad
import Data.Complex
import Data.Maybe
import Text.Printf

type Point = Complex Double
type Vector = Complex Double

eps :: Double
eps = 1e-7

dot :: Vector -> Vector -> Double
dot a b = realPart $ conjugate a * b

cross :: Vector -> Vector -> Double
cross a b = imagPart $ conjugate a * b

normalize :: Vector -> Vector
normalize = signum

readWords :: Read a => IO [a]
readWords = map read . words <$> getLine

data Line = Line {
  a :: Double,
  b :: Double,
  c :: Double
}

data LineSeg = LineSeg {
  p :: Point,
  q :: Point,
  l :: Line
}

mkLine :: Point -> Point -> Line
mkLine p1@(x:+y) p2 = Line a b c where
  (nx:+ny) = (p2-p1)*(0:+1)
  a = nx
  b = ny
  c = -(a*x+b*y)

mkLineSeg :: Point -> Point -> LineSeg
mkLineSeg p1 p2 = LineSeg p1 p2 $ mkLine p1 p2

intersect :: Line -> Line -> Maybe Point
intersect (Line a1 b1 c1) (Line a2 b2 c2)
  | abs ((a1:+b1)`cross`(a2:+b2)) < eps = Nothing
  | otherwise = Just (x/det:+y/det)
  where
    det = a1*b2-b1*a2
    x = c2*b1-c1*b2
    y = a2*c1-a1*c2

intersectLS :: LineSeg -> LineSeg -> Maybe Point
intersectLS (LineSeg p1 q1 l1) (LineSeg p2 q2 l2)
  | cpM == Nothing = Nothing
  | onSeg p1 q1 cp && onSeg p2 q2 cp = Just cp
  | otherwise = Nothing
  where
    cpM = intersect l1 l2
    cp = fromJust cpM
    onSeg p q cp = (cp-p)`dot`(cp-q) < eps
    
main :: IO ()
main = do
  q <- readLn
  qs <- replicateM q $ do
    [x0,y0,x1,y1,x2,y2,x3,y3] <- readWords :: IO [Double]
    let
      p0 = x0:+y0
      p1 = x1:+y1
      p2 = x2:+y2
      p3 = x3:+y3
    return (p0,p1,p2,p3)

  forM_ qs $ \(p0,p1,p2,p3) -> do
    let
      (Just (x:+y)) = intersectLS (mkLineSeg p0 p1) (mkLineSeg p2 p3)
      zero f
        | abs f < eps = 0
        | otherwise = f

    printf "%.10f %.10f\n" (zero x) (zero y)