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 &ne; p1 and
p2 &ne; 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



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

Submission status: Wrong Answer

Solution code:
def cross(c1, c2):
    return c1.real * c2.imag - c1.imag * c2.real

def print_cross_point(p1, p2, p3, p4):
    # p1 and p2 are end points of a segment.
    # p3 and p4 are end points of the other segment.
    base = p4 - p3
    hypo1 = p1 - p3
    hypo2 = p2 - p3
    d1 = abs(cross(base, hypo1)) / abs(base)
    d2 = abs(cross(base, hypo2)) / abs(base)
    cp = p1 + d1 / (d1 + d2) * (p2 - p1)
    print("{0:.10f}, {1:.10f}".format(cp.real, cp.imag))

import sys

file_input = sys.stdin

sq = file_input.readline()

for line in file_input:
    x_p0, y_p0, x_p1, y_p1, x_p2, y_p2, x_p3, y_p3 = map(int, line.split())
    p0 = x_p0 + y_p0 * 1j
    p1 = x_p1 + y_p1 * 1j
    p2 = x_p2 + y_p2 * 1j
    p3 = x_p3 + y_p3 * 1j
    print_cross_point(p0, p1, p2, p3)

Submission status: Wrong Answer

Solution code:
class Line:
    def __init__(self,p1,p2):
        if p1[1] < p2[1]:self.s=p2;self.e=p1
        elif p1[1] > p2[1]:self.s=p1;self.e=p2
        else:
            if p1[0] < p2[0]:self.s=p1;self.e=p2
            else:self.s=p2;self.e=p1

def CrossPoint(l,m):
    f = lambda l : (l.e[1]-l.s[1])/(l.e[0]-l.s[0])
    if l.s[0] == l.e[0]:
        return [l.e[0],f(m) * (l.e[0]-m.s[0])+m.s[1]]
    elif m.s[0] == m.e[0]:
        return [m.e[0],f(l) * (m.e[0]-l.s[0])+l.s[1]]
    A = f(l) ; B = f(m)
    x = (B*m.s[0] - A*l.s[0] + l.s[1] + m.s[1])/(A-B)
    y = A*(x-l.s[0])+l.s[1]
    return [x,y]

q = int(input())
for i in range(q):
    x0,y0,x1,y1,x2,y2,x3,y3 = [int(i) for i in input().split()]
    l = Line([x0,y0],[x1,y1])
    m = Line([x2,y2],[x3,y3])
    P = CrossPoint(l,m)
    print(P[0],P[1])

Submission status: Wrong Answer

Solution code:
q = int(input())
for i in range(q):
    a,b,c,d,e,f,g,h = [int(i) for i in input().split()]
    A = a*d-b*c
    B = e*h-f*g
    C = d-b
    D = c-a
    E = f-h
    F = e-g
    det = C*F - D*E
    print((A*D + B*E)/det,(A*F + B*C)/det)

Submission status: Wrong Answer

Solution code:
q = int(input())
for i in range(q):
    a,b,c,d,e,f,g,h = [int(i) for i in input().split()]
    A = d-b
    B = c-a
    C = f-h
    D = e-g
    E = a*d-b*c
    F = e*h-f*g
    G = A*D-B*C
    print((A*F+B*D)/G,(A*E+B*C)/G)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

import collections
import math


class Vector2(collections.namedtuple("Vector2", ["x",  "y"])):

    def __add__(self, other):
        return Vector2(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Vector2(self.x - other.x, self.y - other.y)

    def __mul__(self, scalar):
        return Vector2(self.x * scalar, self.y * scalar)

    def __neg__(self):
        return Vector2(-self.x, -self.y)

    def __pos__(self):
        return Vector2(+self.x, +self.y)

    def __abs__(self):  # norm
        return math.sqrt(float(self.x * self.x + self.y * self.y))

    def dot(self, other):  # dot product
        return self.x * other.x + self.y * other.y

    def cross(self, other):  # cross product
        return self.x * other.y - self.y * other.x


def getDistanceSP(segment, point):
    p = point
    p1, p2 = segment
    if (p2 - p1).dot(p - p1) < 0:
        return abs(p - p1)
    if (p1 - p2).dot(p - p2) < 0:
        return abs(p - p2)
    return abs((p2 - p1).cross(p - p1)) / abs(p2 - p1)


def getDistance(s1, s2):
    a, b = s1
    c, d = s2
    if intersect(s1, s2):  # intersect
        return 0
    return min(getDistanceSP(s1, c), getDistanceSP(s1, d), getDistanceSP(s2, a), getDistanceSP(s2, b))


def ccw(p0, p1, p2):
    a = p1 - p0
    b = p2 - p0
    if a.cross(b) > 0:
        return 1  # COUNTER_CLOCKWISE
    elif a.cross(b) < 0:
        return -1  # CLOCKWISE
    elif a.dot(b) < 0:
        return 2  # ONLINE_BACK
    elif abs(a) < abs(b):
        return -2  # ONLINE_FRONT
    else:
        return 0  # ON_SEGMENT


def intersect(s1, s2):
    a, b = s1
    c, d = s2
    return ccw(a, b, c) * ccw(a, b, d) <= 0 and ccw(c, d, a) * ccw(c, d, b) <= 0


def getCrossPoint(s1, s2):
    a, b = s1
    c, d = s2
    base = d - c
    d1 = abs(base.cross(b - c))
    d2 = abs(base.cross(a - c))
    t = d1 / (d1 + d2)
    return a + (b - a) * t


if __name__ == '__main__':

    n = int(input())

    for _ in range(n):
        l = list(map(int, input().split()))
        s1 = [Vector2(l[0], l[1]), Vector2(l[2], l[3])]
        s2 = [Vector2(l[4], l[5]), Vector2(l[6], l[7])]

        x = getCrossPoint(s1, s2)
        print(x.x, x.y)

Submission status: Wrong Answer

Solution code:
import math
EPS=1e-10

#点类
class Point():

    def __init__(self,x,y):
        self.x=x
        self.y=y
    
    def __sub__(self,p):
        return Point(self.x - p.x, self.y - p.y);
    def __add__(self,p):
        return Point(self.x + p.x, self.y + p.y)
           
    def __mul__(self,a): #a: scalar
        return Point(self.x * a, self.y * a)
    def __truediv__(self,a): #a: scalar
        return Point(self.x / a, self.y / a)
   
    def __str__(self):
       return  str(self.x)+','+str(self.y)
    def __repr__(self):
        return  'Point('+str(self.x)+','+str(self.y)+')'
    
    def __lt__(self, other):    
        if self.y-other.y==0:
            return self.x<other.x
        else:
            return self.y<other.y
            
    def __eq__(self, other):    
        return abs(self.x-other.x)<EPS and  abs(self.y-other.y)<EPS


# 线段类
class Segment():
    def __init__(self,p1, p2):
        self.p1=p1
        self.p2=p2
    def __str__(self):
        return  'segment:('+str(self.p1)+';'+str(self.p2)+')'
    def __repr__(self):
        return  'segment:('+str(self.p1)+';'+str(self.p2)+')'


class Circle():
    def __init__(self,c, r):
        self.c=c
        self.r=r

    def __str__(self):
       return  'Circle:(center point: '+str(self.c)+'; radius: '+str(self.r)+')'
    def __repr__(self):
       return  'Circle:(center point: '+str(self.c)+'; radius: '+str(self.r)+')'
   
    
#定义多边形
class Polygon():
    def __init__(self,ps=[]):
        self.ps=ps
        self.size=len(ps)
  
    def __getitem__(self, i):#iter override 
        return self.ps[i]  
    def __setitem__(self,i,p): 
        self.ps[i]=p               
    def __iter__(self):     
        return self.ps  
    
    def addpoint(self,i,p):
        self.ps.insert(i,p)
        self.size+=1
    def delpoint(self,i):
        self.size-=1
        return self.ps.pop(i)
    def sortYX(self):
        self.ps.sort()
        #self.ps.sort(key=attrgetter('y','x'))
    def __str__(self):
       return  'Polygon:'+str(tuple(self.ps))
    def __repr__(self):
       return  'Polygon:'+str(tuple(self.ps))
        
    def __len__(self):
        return len(self.ps)
    def __eq__(self, other):  
         return self.ps==other.ps
    
    def draw(self):
      
       turtle.screensize(800,800,"black")
       #turtle.setup(width=0.9,height=0.9)
       turtle.title("Polygon convex hull")
       turtle.setworldcoordinates(-400,-400,400,400) 

       #print(turtle.screensize())
       #mywin = turtle.Screen()    
       #mywin.   
       t=turtle.Turtle() 
       #mywin=turtle.Screen()
       
       t.pencolor("red")
       for pt in self.ps:
           t.goto(pt.x,pt.y)
           t.dot(10,'white')
       
 

#***************************点、向量****************************

#向量的模的平方
def norm(p):  
    return p.x * p.x + p.y * p.y


#向量P的长度
def length(p):
    return math.sqrt(p.x * p.x + p.y * p.y)


# 向量的(点)内积, dot(a,b)=|a|*|b|*cos(a,b) (从a,到b的角)
# =============================================================================
# r=dot(a,b),得到矢量a和b的点积，如果两个矢量都非零矢量  
# r<0：两矢量夹角为钝角； 
# r=0：两矢量夹角为直角； 
# r>0：两矢量夹角为锐角  
# =============================================================================
def dot(a, b) :
    return a.x * b.x + a.y * b.y



# =============================================================================
# # 向量的（叉）外积 cross(a,b)=|a||b|*sin(a,b) (从a,到b的角)由a,b构成的平行四边的面积
# r=cross(a,b),得到向量a和向量b的叉积  
# r>0：b在矢量a的逆时针方向；  
# r=0：a,b 平行共线；  
# r<0：b在向量a的顺时针方向 
# =============================================================================
def cross( a, b) :
    return a.x * b.y - a.y * b.x

# 点p在线段s上的投影
def project(s, p):
    base = s.p2 - s.p1
    r = dot(p - s.p1, base) / norm(base)
    return s.p1 + base * r 


# 点a到点b的距离
def getDistance(a, b) :
    return length(a - b)

# 线段l和点p的距离
def getDistanceLP(l, p) :
    return abs( cross(l.p2 - l.p1, p - l.p1) / length(l.p2 - l.p1) )

#getDistanceLP(s3, p7)
    
#线段s与点p的距离
def getDistanceSP(s, p) :
    if (dot(s.p2 - s.p1, p - s.p1) < 0.0):
        return length(p - s.p1)
    if (dot(s.p1 - s.p2, p - s.p2) < 0.0):
        return length(p - s.p2)
    return getDistanceLP(s, p)

#print(getDistanceLP(s3, Point(5,5)))
#print(getDistanceSP(s3, Point(5,5)))


#*************************线段********************************/
# 线段s1，s2是否正交 <==> 内积为0
def isOrthogonalSG(s1, s2) :
    return abs(dot(s1.p2 - s1.p1, s2.p2 - s2.p1))<EPS


# 线段s1，s2是否平行 <==> 叉积为0
def isParallelLN(s1,s2) :
    return abs(cross(s1.p2 - s1.p1, s2.p2 - s2.p1))<0




# 逆时针方向ccw（Counter-Clockwise）
COUNTER_CLOCKWISE = 1;
CLOCKWISE = -1;
ONLINE_BACK = -2;
ONLINE_FRONT = 2;
ON_SEGMENT = 0;

def ccw(p0, p1, p2) :
    a = p1 - p0
    b = p2 - p0
    if (cross(a, b) > EPS):
        return COUNTER_CLOCKWISE
    if (cross(a, b) < -EPS):
        return CLOCKWISE
    if (dot(a, b) < -EPS):
        return ONLINE_BACK
    if (norm(a) < norm(b)):
        return ONLINE_FRONT
    
    return ON_SEGMENT;


def toleft(p0,p1,p2):
    a = p1 - p0
    b = p2 - p0  
    tmp=cross(a,b)
    if tmp > EPS:
        return 1
    elif abs(tmp)<EPS and norm(a)<=norm(b):
        return 2  #共线，p2在p0p1的右延长线上
    elif abs(tmp)<EPS and norm(a)>norm(b):
        return -2  #共线，p2在p0p1的left延长线上    
    else:
        return -1


#以线段s为对称轴与点p成线对称的点
def reflect(s, p) :
    return p + (project(s, p) - p) * 2.0



#判断线段s1和s2是否相交
def intersectSG(s1, s2) :
    return intersectP4(s1.p1, s1.p2, s2.p1, s2.p2)


# 线段s1和线段s2的距离
def getDistanceSG(s1, s2) :
    # 相交
    if (intersectSG(s1, s2)):
        return 0.0
    return min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2),\
        getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2))

# 判断线段p1p2和线段p3p4是否相交
def intersectP4(p1, p2, p3, p4) :
    return ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 and \
            ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0


# 线段s1与线段s2的交点
def getCrossPoint(s1,s2) :
    base = s2.p2 - s2.p1;
    d1 = abs(cross(base, s1.p1 - s2.p1));
    d2 = abs(cross(base, s1.p2 - s2.p1));
    t = d1 / (d1 + d2);
    return s1.p1 + (s1.p2 - s1.p1) * t;
                                                                                                                                                       


q=int(input())
for i in range(0,q):
    s= [int(x) for x in input().split()]
    p0=Point(s[0],s[1])
    p1=Point(s[2],s[3])
    p2=Point(s[4],s[5])
    p3=Point(s[6],s[7])
    s1=Segment(p0,p1)
    s2=Segment(p2,p3)
    rt=getCrossPoint(s1,s2)
    print("{:.12f},{:.12f}".format(rt.x,rt.y))

Submission status: Wrong Answer

Solution code:
import math
EPS=1e-14

#点类
class Point():

    def __init__(self,x,y):
        self.x=x
        self.y=y
    
    def __sub__(self,p):
        return Point(self.x - p.x, self.y - p.y);
    def __add__(self,p):
        return Point(self.x + p.x, self.y + p.y)
           
    def __mul__(self,a): #a: scalar
        return Point(self.x * a, self.y * a)
    def __truediv__(self,a): #a: scalar
        return Point(self.x / a, self.y / a)
   
    def __str__(self):
       return  str(self.x)+','+str(self.y)
    def __repr__(self):
        return  'Point('+str(self.x)+','+str(self.y)+')'
    
    def __lt__(self, other):    
        if self.y-other.y==0:
            return self.x<other.x
        else:
            return self.y<other.y
            
    def __eq__(self, other):    
        return abs(self.x-other.x)<EPS and  abs(self.y-other.y)<EPS


# 线段类
class Segment():
    def __init__(self,p1, p2):
        self.p1=p1
        self.p2=p2
    def __str__(self):
        return  'segment:('+str(self.p1)+';'+str(self.p2)+')'
    def __repr__(self):
        return  'segment:('+str(self.p1)+';'+str(self.p2)+')'


class Circle():
    def __init__(self,c, r):
        self.c=c
        self.r=r

    def __str__(self):
       return  'Circle:(center point: '+str(self.c)+'; radius: '+str(self.r)+')'
    def __repr__(self):
       return  'Circle:(center point: '+str(self.c)+'; radius: '+str(self.r)+')'
   
    
#定义多边形
class Polygon():
    def __init__(self,ps=[]):
        self.ps=ps
        self.size=len(ps)
  
    def __getitem__(self, i):#iter override 
        return self.ps[i]  
    def __setitem__(self,i,p): 
        self.ps[i]=p               
    def __iter__(self):     
        return self.ps  
    
    def addpoint(self,i,p):
        self.ps.insert(i,p)
        self.size+=1
    def delpoint(self,i):
        self.size-=1
        return self.ps.pop(i)
    def sortYX(self):
        self.ps.sort()
        #self.ps.sort(key=attrgetter('y','x'))
    def __str__(self):
       return  'Polygon:'+str(tuple(self.ps))
    def __repr__(self):
       return  'Polygon:'+str(tuple(self.ps))
        
    def __len__(self):
        return len(self.ps)
    def __eq__(self, other):  
         return self.ps==other.ps
    
    def draw(self):
      
       turtle.screensize(800,800,"black")
       #turtle.setup(width=0.9,height=0.9)
       turtle.title("Polygon convex hull")
       turtle.setworldcoordinates(-400,-400,400,400) 

       #print(turtle.screensize())
       #mywin = turtle.Screen()    
       #mywin.   
       t=turtle.Turtle() 
       #mywin=turtle.Screen()
       
       t.pencolor("red")
       for pt in self.ps:
           t.goto(pt.x,pt.y)
           t.dot(10,'white')
       
 

#***************************点、向量****************************

#向量的模的平方
def norm(p):  
    return p.x * p.x + p.y * p.y


#向量P的长度
def length(p):
    return math.sqrt(p.x * p.x + p.y * p.y)


# 向量的(点)内积, dot(a,b)=|a|*|b|*cos(a,b) (从a,到b的角)
# =============================================================================
# r=dot(a,b),得到矢量a和b的点积，如果两个矢量都非零矢量  
# r<0：两矢量夹角为钝角； 
# r=0：两矢量夹角为直角； 
# r>0：两矢量夹角为锐角  
# =============================================================================
def dot(a, b) :
    return a.x * b.x + a.y * b.y



# =============================================================================
# # 向量的（叉）外积 cross(a,b)=|a||b|*sin(a,b) (从a,到b的角)由a,b构成的平行四边的面积
# r=cross(a,b),得到向量a和向量b的叉积  
# r>0：b在矢量a的逆时针方向；  
# r=0：a,b 平行共线；  
# r<0：b在向量a的顺时针方向 
# =============================================================================
def cross( a, b) :
    return a.x * b.y - a.y * b.x

# 点p在线段s上的投影
def project(s, p):
    base = s.p2 - s.p1
    r = dot(p - s.p1, base) / norm(base)
    return s.p1 + base * r 


# 点a到点b的距离
def getDistance(a, b) :
    return length(a - b)

# 线段l和点p的距离
def getDistanceLP(l, p) :
    return abs( cross(l.p2 - l.p1, p - l.p1) / length(l.p2 - l.p1) )

#getDistanceLP(s3, p7)
    
#线段s与点p的距离
def getDistanceSP(s, p) :
    if (dot(s.p2 - s.p1, p - s.p1) < 0.0):
        return length(p - s.p1)
    if (dot(s.p1 - s.p2, p - s.p2) < 0.0):
        return length(p - s.p2)
    return getDistanceLP(s, p)

#print(getDistanceLP(s3, Point(5,5)))
#print(getDistanceSP(s3, Point(5,5)))


#*************************线段********************************/
# 线段s1，s2是否正交 <==> 内积为0
def isOrthogonalSG(s1, s2) :
    return abs(dot(s1.p2 - s1.p1, s2.p2 - s2.p1))<EPS


# 线段s1，s2是否平行 <==> 叉积为0
def isParallelLN(s1,s2) :
    return abs(cross(s1.p2 - s1.p1, s2.p2 - s2.p1))<0




# 逆时针方向ccw（Counter-Clockwise）
COUNTER_CLOCKWISE = 1;
CLOCKWISE = -1;
ONLINE_BACK = -2;
ONLINE_FRONT = 2;
ON_SEGMENT = 0;

def ccw(p0, p1, p2) :
    a = p1 - p0
    b = p2 - p0
    if (cross(a, b) > EPS):
        return COUNTER_CLOCKWISE
    if (cross(a, b) < -EPS):
        return CLOCKWISE
    if (dot(a, b) < -EPS):
        return ONLINE_BACK
    if (norm(a) < norm(b)):
        return ONLINE_FRONT
    
    return ON_SEGMENT;


def toleft(p0,p1,p2):
    a = p1 - p0
    b = p2 - p0  
    tmp=cross(a,b)
    if tmp > EPS:
        return 1
    elif abs(tmp)<EPS and norm(a)<=norm(b):
        return 2  #共线，p2在p0p1的右延长线上
    elif abs(tmp)<EPS and norm(a)>norm(b):
        return -2  #共线，p2在p0p1的left延长线上    
    else:
        return -1


#以线段s为对称轴与点p成线对称的点
def reflect(s, p) :
    return p + (project(s, p) - p) * 2.0



#判断线段s1和s2是否相交
def intersectSG(s1, s2) :
    return intersectP4(s1.p1, s1.p2, s2.p1, s2.p2)


# 线段s1和线段s2的距离
def getDistanceSG(s1, s2) :
    # 相交
    if (intersectSG(s1, s2)):
        return 0.0
    return min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2),\
        getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2))

# 判断线段p1p2和线段p3p4是否相交
def intersectP4(p1, p2, p3, p4) :
    return ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 and \
            ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0


# 线段s1与线段s2的交点
def getCrossPoint(s1,s2) :
    base = s2.p2 - s2.p1;
    d1 = abs(cross(base, s1.p1 - s2.p1));
    d2 = abs(cross(base, s1.p2 - s2.p1));
    if d1+d2==0:
        return s2.p1
    t = d1 / (d1 + d2);
    return s1.p1 + (s1.p2 - s1.p1) * t;
                                                                                                                                                       


q=int(input())
for i in range(0,q):
    s= [int(x) for x in input().split()]
    p0=Point(s[0],s[1])
    p1=Point(s[2],s[3])
    p2=Point(s[4],s[5])
    p3=Point(s[6],s[7])
    s1=Segment(p0,p1)
    s2=Segment(p2,p3)
    rt=getCrossPoint(s1,s2)
    print("{:.12f},{:.12f}".format(rt.x,rt.y))

Submission status: Accepted

Solution code:
def dot(a, b):
  return a.real * b.real + a.imag * b.imag

def cross(a, b):
  return a.real * b.imag - a.imag * b.real

def cross_point(p0,p1,p2,p3):
  base=p3-p2
  d1=abs(cross(base,p0-p2))
  d2=abs(cross(base,p1-p2))
  t=d1/(d1+d2)
  ans= p0+(p1-p0)*t
  return ans.real,ans.imag

n = int(input())
for i in range(n):
  x0,y0,x1,y1,x2,y2,x3,y3 = map(int,input().split())
  p0=complex(x0,y0)
  p1=complex(x1,y1)
  p2=complex(x2,y2)
  p3=complex(x3,y3)
  print(*cross_point(p0,p1,p2,p3))

Submission status: Accepted

Solution code:
from sys import stdin

class Vector:
    def __init__(self, x=None, y=None):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Vector(self.x - other.x, self.y - other.y)

    def __mul__(self, k):
        return Vector(self.x * k, self.y * k)

    def __gt__(self, other):
        return self.x > other.x and self.y > other.yb

    def __lt__(self, other):
        return self.x < other.x and self.y < other.yb

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def dot(self, other):
        return self.x * other.x + self.y * other.y

    # usually cross operation return Vector but it returns scalor
    def cross(self, other):
        return self.x * other.y - self.y * other.x

    def norm(self):
        return self.x * self.x + self.y * self.y

    def abs(self):
        return math.sqrt(self.norm())

class Point(Vector):
    def __init__(self, *args, **kargs):
        return super().__init__(*args, **kargs)

class Segment:
    def __init__(self, p1=Point(0, 0), p2=Point(1, 1)):
        self.p1 = p1
        self.p2 = p2

def get_cross_point(s1, s2):
    base = s2.p2 - s2.p1
    hypo1 = s1.p1 - s2.p1
    hypo2 = s1.p2 - s2.p1
    d1 = abs(base.cross(hypo1))
    d2 = abs(base.cross(hypo2))
    t = d1 / (d1 + d2)
    return s1.p1 + (s1.p2 - s1.p1) * t

def read_and_print_results(n):
    for _ in range(n):
        line = stdin.readline().strip().split()
        p0 = Vector(int(line[0]), int(line[1]))
        p1 = Vector(int(line[2]), int(line[3]))
        p2 = Vector(int(line[4]), int(line[5]))
        p3 = Vector(int(line[6]), int(line[7]))
        s1 = Segment(p0, p1)
        s2 = Segment(p2, p3)
        p = get_cross_point(s1, s2)
        print("{0:0.10f} {1:0.10f}".format(p.x, p.y))

n = int(input())
read_and_print_results(n)

Submission status: Accepted

Solution code:
from sys import stdin
readline = stdin.readline


def main():
    q = int(readline())
    for i in range(q):
        xy = map(int, readline().split())
        p0, p1, p2, p3 = [x + y * 1j for x, y in zip(*[xy] * 2)]
        c1 = intersection(p0, p2, p1, p3)
        print('{:.10f} {:.10f}'.format(c1.real, c1.imag))


# http://imagingsolution.blog107.fc2.com/blog-entry-137.html
def intersection(p1, p2, p3, p4):
    a1 = p4 - p2
    b1 = p2 - p3
    b2 = p1 - p2
    s1 = cross(a1, b2) / 2
    s2 = cross(a1, b1) / 2
    c1 = p1 + (p3 - p1) * s1 / (s1 + s2)
    return c1


def cross(a, b):
    return a.real * b.imag - a.imag * b.real
main()

Submission status: Accepted

Solution code:
from itertools import starmap


def cross(a, b):
    return a.real * b.imag - a.imag * b.real


q = int(input())
while q:
    q -= 1
    p0, p1, p2, p3 = starmap(complex, zip(*[map(int, input().split())] * 2))
    d1, d2 = abs(cross(p3 - p2, p0 - p2)), abs(cross(p3 - p2, p1 - p2))
    c = p0 + (p1 - p0) * d1 / (d1 + d2)
    print(c.real, c.imag)

Submission status: Accepted

Solution code:
for t in xrange(input()):
    x0, y0, x1, y1, x2, y2, x3, y3 = map(int, raw_input().split())
    dx0 = x1 - x0
    dy0 = y1 - y0
    dx1 = x3 - x2
    dy1 = y3 - y2

    s = (y0-y2)*dx1 - (x0-x2)*dy1
    sm = dx0*dy1 - dy0*dx1
    if s < 0:
        s = -s
        sm = -sm
    t = (y2-y0)*dx0 - (x2-x0)*dy0
    tm = dx1*dy0 - dy1*dx0
    if t < 0:
        t = -t
        tm = -tm
    if s == 0:
        x = x0
        y = y0
    else:
        x = x0 + s*dx0/float(sm)
        y = y0 + s*dy0/float(sm)
    print "%.09f %.09f" % (x, y)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
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

output:
1.0000000000 0.0000000000
0.5000000000 0.5000000000
0.5000000000 0.5000000000
"""

import sys


class Segment(object):
    __slots__ = ('source', 'target')

    def __init__(self, source, target):
        self.source = complex(source)
        self.target = complex(target)


def cross(a, b):
    return a.real * b.imag - a.imag * b.real


def dot(a, b):
    return a.real * b.real + a.imag * b.imag


def get_cross_point(s1, s2):
    base_vector = s2.target - s2.source
    d1 = abs(cross(base_vector, s1.source - s2.source))
    d2 = abs(cross(base_vector, s1.target - s2.source))
    t = d1 / (d1 + d2)
    cross_point = s1.source + (s1.target - s1.source) * t
    print('{real:.10f} {imag:.10f}'.format(real=cross_point.real, imag=cross_point.imag))

    return None


def solve(_lines):
    for line in _lines:
        line = tuple(map(int, line))
        p0, p1, p2, p3 = (x + y * 1j for x, y in zip(line[::2], line[1::2]))
        s1, s2 = Segment(p0, p1), Segment(p2, p3)
        get_cross_point(s1, s2)

    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    l_num = int(_input[0])
    lines = map(lambda x: x.split(), _input[1:])

    solve(lines)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
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

output:
1.0000000000 0.0000000000
0.5000000000 0.5000000000
0.5000000000 0.5000000000
"""

import sys
from collections import namedtuple


def cross(a, b):
    return a.real * b.imag - a.imag * b.real


def dot(a, b):
    return a.real * b.real + a.imag * b.imag


def get_cross_point(s1, s2):
    base_vector = s2.target - s2.source
    d1 = abs(cross(base_vector, s1.source - s2.source))
    d2 = abs(cross(base_vector, s1.target - s2.source))
    t = d1 / (d1 + d2)
    cross_point = s1.source + (s1.target - s1.source) * t
    print('{real:.10f} {imag:.10f}'.format(real=cross_point.real, imag=cross_point.imag))

    return None


def solve(_segments):
    for segment in _segments:
        segment = tuple(map(int, segment))
        p0, p1, p2, p3 = (x + y * 1j for x, y in zip(segment[::2], segment[1::2]))
        s1, s2 = Segment(p0, p1), Segment(p2, p3)
        get_cross_point(s1, s2)

    return None


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    l_num = int(_input[0])
    segments = map(lambda x: x.split(), _input[1:])
    Segment = namedtuple('Segment', ('source', 'target'))
    solve(segments)

Submission status: Accepted

Solution code:
def cross(c1, c2):
    return c1.real * c2.imag - c1.imag * c2.real

def print_cross_point(p1, p2, p3, p4):
    # p1 and p2 are end points of a segment.
    # p3 and p4 are end points of the other segment.
    base = p4 - p3
    hypo1 = p1 - p3
    hypo2 = p2 - p3
    d1 = abs(cross(base, hypo1)) / abs(base)
    d2 = abs(cross(base, hypo2)) / abs(base)
    cp = p1 + d1 / (d1 + d2) * (p2 - p1)
    print("{0:.10f} {1:.10f}".format(cp.real, cp.imag))

import sys

file_input = sys.stdin

sq = file_input.readline()

for line in file_input:
    x_p0, y_p0, x_p1, y_p1, x_p2, y_p2, x_p3, y_p3 = map(int, line.split())
    p0 = x_p0 + y_p0 * 1j
    p1 = x_p1 + y_p1 * 1j
    p2 = x_p2 + y_p2 * 1j
    p3 = x_p3 + y_p3 * 1j
    print_cross_point(p0, p1, p2, p3)

Submission status: Accepted

Solution code:
def intersection_ll(S0, S1, T0, T1):
    x0, y0 = S0; x1, y1 = S1
    X0, X1 = T0; X1, Y1 = T1
    p = (x1-x0)*(y0-Y0) - (y1-y0)*(x0-X0) # -cross(S0, S1, T0)
    q = (x1-x0)*(Y1-Y0) - (y1-y0)*(X1-X0) # cross(0, S1-S0, T1-T0)
    return (X0 + p*(X1-X0)/float(q), Y0 + p*(Y1-Y0)/float(q))# T0 + p/q*(T1-T0)

n = int(input())
for i in range(n):
    x0, y0, x1, y1, X0, Y0, X1, Y1 = map(int, input().split())
    print("%.08f %.08f" % intersection_ll((x0, y0), (x1, y1), (X0, Y0), (X1, Y1)))

Submission status: Accepted

Solution code:
import sys
from itertools import starmap
readline = sys.stdin.readline
EPS = 1e-9
ONLINE_FRONT = -2
CLOCKWISE = -1
ON_SEGMENT = 0
COUNTER_CLOCKWISE = 1
ONLINE_BACK = 2
class Segment(object):
    __slots__ = ('fi', 'se')
    def __init__(self, fi, se):
        self.fi = fi
        self.se = se
def cross(a, b):
    return a.real * b.imag - a.imag * b.real
def dot(a, b):
    return a.real * b.real + a.imag * b.imag
def norm(base):
    return abs(base) ** 2
def project(s, p2):
    base = s.fi - s.se
    r = dot(p2 - s.fi, base) / norm(base)
    return s.fi + base * r
def reflect(s, p):
    return p + (project(s, p) - p) * 2.0
def ccw(p1, p2, p3):
    a = p2 - p1
    b = p3 - p1
    if cross(a, b) > EPS: return 1
    if cross(a, b) < -EPS: return -1
    if dot(a, b) < -EPS: return 2
    if norm(a) < norm(b): return -2
    return 0
def intersect4(p1, p2, p3, p4):
    return (ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 and
			ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0)
def intersect2(s1, s2):
    return intersect4(s1.fi, s1.se, s2.fi, s2.se)
def getDistance(a, b):  return abs(a - b)
def getDistanceLP(l, p):
    return abs(cross(l.se - l.fi, p - l.fi) / abs(l.se - l.fi))
def getDistanceSP(s, p):
    if dot(s.se - s.fi, p - s.fi) < 0.0: return abs(p - s.fi)
    if dot(s.fi - s.se, p - s.se) < 0.0: return abs(p - s.se)
    return getDistanceLP(s, p)
def getDistances(s1, s2):
    if intersect2(s1, s2): return 0.0
    return min(getDistanceSP(s1, s2.fi), getDistanceSP(s1, s2.se),
               getDistanceSP(s2, s1.fi), getDistanceSP(s2, s1.se))
def getCrossPoint(s1, s2):
	base = s2.se - s2.fi
	d1 = abs(cross(base, s1.fi - s2.fi))
	d2 = abs(cross(base, s1.se - s2.fi))
	t = d1 / (d1 + d2)
	return s1.fi + (s1.se - s1.fi) * t
n = int(readline())
for _ in [0] * n:
    p0, p1, p2, p3 = starmap(complex, zip(*[map(int, input().split())] * 2))
    p = getCrossPoint(Segment(p0, p1), Segment(p2, p3))
    print("{0:.10f} {1:.10f}".format(p.real, p.imag))

Submission status: Accepted

Solution code:
import sys
from itertools import starmap
readline = sys.stdin.readline
EPS = 1e-9
ONLINE_FRONT = -2
CLOCKWISE = -1
ON_SEGMENT = 0
COUNTER_CLOCKWISE = 1
ONLINE_BACK = 2
class Segment(object):
    __slots__ = ('fi', 'se')
    def __init__(self, fi, se):
        self.fi = fi
        self.se = se
def cross(a, b):
    return a.real * b.imag - a.imag * b.real
def dot(a, b):
    return a.real * b.real + a.imag * b.imag
def norm(base):
    return abs(base) ** 2
def project(s, p2):
    base = s.fi - s.se
    r = dot(p2 - s.fi, base) / norm(base)
    return s.fi + base * r
def reflect(s, p):
    return p + (project(s, p) - p) * 2.0
def ccw(p1, p2, p3):
    a = p2 - p1
    b = p3 - p1
    if cross(a, b) > EPS: return 1
    if cross(a, b) < -EPS: return -1
    if dot(a, b) < -EPS: return 2
    if norm(a) < norm(b): return -2
    return 0
def intersect4(p1, p2, p3, p4):
    return (ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 and
			ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0)
def intersect2(s1, s2):
    return intersect4(s1.fi, s1.se, s2.fi, s2.se)
def getDistance(a, b):  return abs(a - b)
def getDistanceLP(l, p):
    return abs(cross(l.se - l.fi, p - l.fi) / abs(l.se - l.fi))
def getDistanceSP(s, p):
    if dot(s.se - s.fi, p - s.fi) < 0.0: return abs(p - s.fi)
    if dot(s.fi - s.se, p - s.se) < 0.0: return abs(p - s.se)
    return getDistanceLP(s, p)
def getDistances(s1, s2):
    if intersect2(s1, s2): return 0.0
    return min(getDistanceSP(s1, s2.fi), getDistanceSP(s1, s2.se),
               getDistanceSP(s2, s1.fi), getDistanceSP(s2, s1.se))
def getCrossPoint(s1, s2):
	base = s2.se - s2.fi
	d1 = abs(cross(base, s1.fi - s2.fi))
	d2 = abs(cross(base, s1.se - s2.fi))
	t = d1 / (d1 + d2)
	return s1.fi + (s1.se - s1.fi) * t
n = int(readline())
for _ in [0] * n:
    p0, p1, p2, p3 = starmap(complex, zip(*[map(int, readline().split())] * 2))
    p = getCrossPoint(Segment(p0, p1), Segment(p2, p3))
    print("{0:.10f} {1:.10f}".format(p.real, p.imag))

Submission status: Accepted

Solution code:
class Line:
    def __init__(self,p1,p2):
        if p1[1] < p2[1]:self.s=p2;self.e=p1
        elif p1[1] > p2[1]:self.s=p1;self.e=p2
        else:
            if p1[0] < p2[0]:self.s=p1;self.e=p2
            else:self.s=p2;self.e=p1

def cross(a,b):return a[0]*b[1] - a[1]*b[0]
def CrossPoint(l,m):
    crsl = cross(l.s,l.e)
    crsm = cross(m.s,m.e)
    det = (l.s[1] - l.e[1])*(m.e[0] - m.s[0]) - (l.e[0]-l.s[0])*(m.s[1]-m.e[1])
    x = (m.s[0] - m.e[0]) * crsl + (l.e[0] - l.s[0]) * crsm
    y = (m.s[1] - m.e[1]) * crsl + (l.e[1] - l.s[1]) * crsm
    return [x/det,y/det]

q = int(input())
for i in range(q):
    x0,y0,x1,y1,x2,y2,x3,y3 = [int(i) for i in input().split()]
    l = Line([x0,y0],[x1,y1])
    m = Line([x2,y2],[x3,y3])
    P = CrossPoint(l,m)
    print(P[0],P[1])

Submission status: Accepted

Solution code:
def cp(a,b,c,d,e,f,g,h):
    A = a*d-b*c
    B = e*h-f*g
    C = d-b
    D = e-g
    E = c-a
    F = f-h
    det = C*D - E*F
    x = A*D + B*E
    y = A*F + B*C
    return [x/det,y/det]

q = int(input())
for i in range(q):
    a,b,c,d,e,f,g,h = [int(i) for i in input().split()]
    P = cp(a,b,c,d,e,f,g,h)
    print(P[0],P[1])