Problem:


Projection

For given three points p1, p2, p, find the projection point x of p onto p1p2.

Input

xp1 yp1 xp2 yp2
q
xp0 yp0
xp1 yp1
...
xpq&minus;1 ypq&minus;1

In the first line, integer coordinates of p1 and p2 are given. Then, q queries are given for integer coordinates of p.

Output

xt0 yt0
xt1 yt1
...
xtq-1 ytq-1

-->

For each query, print the coordinate of the projection point x. The output values should be in a decimal fraction with an error less than 0.00000001.

Constraints

1 ≤ q ≤ 1000

-10000 ≤ xi, yi ≤ 10000

p1 and p2 are not identical.

Sample Input 1

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

Sample Output 1

-1.0000000000 0.0000000000
0.0000000000 0.0000000000
1.0000000000 0.0000000000

Sample Input 2

0 0 3 4
1
2 5

Sample Output 2

3.1200000000 4.1600000000



Sample input:
0 0 2 0
3
-1 1
0 1
1 1


Sample output:
-1.0000000000 0.0000000000
0.0000000000 0.0000000000
1.0000000000 0.0000000000

Submission status: Accepted

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):  # cross product
        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


if __name__ == '__main__':

    a, b, c, d = map(int, input().split())
    p1 = Vector2(a, b)
    p2 = Vector2(c, d)
    base = p2 - p1
    q = int(input())

    for _ in range(q):
        e, f = map(int, input().split())
        hypo = Vector2(e - a, f - b)
        x = p1 + base * (hypo.dot(base) / abs(base)**2)

        print(x.x, x.y)

Submission status: Accepted

Solution code:
import math

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

class Vector():
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.abs = math.sqrt(x*x + y*y)

    def constant_multipled(self, c):
        return Vector(self.x*c, self.y*c)

    def inner_product(self, vec):
        return self.x*vec.x + self.y*vec.y

x1, y1, x2, y2 = list(map(int, input().split(' ')))
start = Point(x1, y1)
base_vec = Vector(x2-x1, y2-y1)
q = int(input())
vectors = []
for i in range(q):
    x, y = list(map(int, input().split(' ')))
    vectors.append(Vector(x-start.x, y-start.y))

for vec in vectors:
    if vec.abs == 0:
        ans_x, ans_y = 0, 0
        print('%.8f'%ans_x, '%.8f'%ans_y)
        continue
    cos = base_vec.inner_product(vec)/(base_vec.abs*vec.abs)
    b_cos = vec.abs*cos
    vec_x = base_vec.constant_multipled(b_cos/base_vec.abs)
    ans_x, ans_y = vec_x.x + start.x, vec_x.y + start.y
    print('%.8f'%ans_x, '%.8f'%ans_y)

Submission status: Accepted

Solution code:
# coding=utf-8
from math import sqrt


def inner_product(vect1, vect2):
    return sum([(v1_el*v2_el) for v1_el, v2_el in zip(vect1, vect2)])


def vector_abs(vect):
    return sqrt(sum([element**2 for element in vect]))


def direction_unit_vector(p_from, p_to):
    d_vector = [(xt - xf) for xt, xf in zip(p_to, p_from)]
    d_u_vector = [element/vector_abs(d_vector) for element in d_vector]
    return d_u_vector


def projection(origin, line_from, line_to):
    direction_unit = direction_unit_vector(line_from, line_to)
    origin_d_vector = [(org-lf) for org, lf in zip(origin, line_from)]
    inject_dist = inner_product(direction_unit, origin_d_vector)
    on_line_vect = [inject_dist*element for element in direction_unit]
    return [olv_el + lf_el for olv_el, lf_el in zip(on_line_vect, line_from)]


if __name__ == '__main__':
    xy_list = list(map(int, input().split()))
    p1_list = xy_list[:2]
    p2_list = xy_list[2:]
    Q = int(input())

    for i in range(Q):
        p_list = list(map(int, input().split()))
        x_list = projection(p_list, p1_list, p2_list)
        print(' '.join(map(str, x_list)))

Submission status: Accepted

Solution code:
class Point():
	def __init__(self, x, y):
		self.x = x
		self.y = y
	

output_list = []


init_point = map(float, raw_input().split())

p0 = Point(init_point[0], init_point[1])
p1 = Point(init_point[2], init_point[3])


q = int(raw_input())
datalist = [map(float, raw_input().split()) for i in range(q)]


#p0--p1 : y=ax+b
#p2--t  : y=cx+d

if (p0.x - p1.x) == 0:
	for data in datalist:
		p2 = Point(data[0], data[1])
		output_list.append( (p0.x, p2.y) )

elif (p0.y - p1.y) == 0:
	for data in datalist:
		p2 = Point(data[0], data[1])
		output_list.append( (p2.x, p0.y) )
		
else:
	a = (p0.y - p1.y) / (p0.x - p1.x)
	c = -1/a
	b = p0.y - a*p0.x
	
	for data in datalist:
		p2 = Point(data[0], data[1])
		
		d = p2.y - c*p2.x
		
		X = (-b+d) / (a-c)
		Y = a*X + b
		
		output_list.append( (X,Y) )
		
for x, y in output_list:
	print "%.10f %.10f" % (x, y)

Submission status: Accepted

Solution code:
from math import hypot

x1, y1, x2, y2 = map(int, input().split())
dx, dy = x2-x1, y2-y1
vector_base = hypot(dx, dy)
q = int(input())

for i in range(q):
    x3, y3 = map(int, input().split()) 
    d = ((x3-x1)*dx + (y3-y1)*dy) / (vector_base**2)
    print(x1+dx*d, y1+dy*d)

Submission status: Accepted

Solution code:
from math import sin, cos, atan2

def sgn(x, eps=1e-10):
    if x < -eps: return -1
    if -eps <= x <= eps: return 0
    if eps < x: return 1

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

    def arg(self):
        return atan2(self.y, self.x)

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

    def rotate(self, t):
        nx = self.x * cos(t) - self.y * sin(t)
        ny = self.x * sin(t) + self.y * cos(t)
        return Vector(nx, ny)

    def counter(self):
        nx = -self.x
        ny = -self.y
        return Vector(nx, ny)

    def times(self, k):
        nx = self.x * k
        ny = self.y * k
        return Vector(nx, ny)

    def unit(self):
        norm = self.norm()
        nx = self.x / norm
        ny = self.y / norm
        return Vector(nx, ny)

    def normal(self):
        norm = self.norm()
        nx = -self.y / norm
        ny = self.x / norm
        return Vector(nx, ny)

    def add(self, other): #Vector, Vector -> Vector
        nx = self.x + other.x
        ny = self.y + other.y
        return Vector(nx, ny)

    def sub(self, other):
        nx = self.x - other.x
        ny = self.y - other.y
        return Vector(nx, ny)

    def dot(self, other): #Vector, Vector -> int
        return self.x * other.x + self.y * other.y

    def cross(self, other): #Vector, Vector -> int
        return self.x * other.y - self.y * other.x

    def __str__(self):
        return str(self.x) + ' ' + str(self.y)

class Line():
    def __init__(self, bgn=Vector(), end=Vector()):
        self.bgn = bgn
        self.end = end

    def build(self, a, b, c): #ax + by == 1
        assert sgn(a) != 0 or sgn(b) != 0
        if sgn(b) == 0:
            self.bgn = Vector(-c / a, 0.0)
            self.end = Vector(-c / a, 1.0)
        else:
            self.v = Vector(0, -c / b)
            self.u = Vector(1.0, -(a + b) / b)

    def vec(self):
        return self.end.sub(self.bgn)

    def projection(self, point):
        v = self.vec()
        u = point.sub(self.bgn)
        k = v.dot(u) / v.norm()
        h = v.unit().times(k)
        return self.bgn.add(h)

xp1, yp1, xp2, yp2 = map(int, input().split())
q = int(input())

p1 = Vector(xp1, yp1)
p2 = Vector(xp2, yp2)
l = Line(p1, p2)

for _ in range(q):
    x, y = map(int, input().split())
    p = Vector(x, y)
    proj = l.projection(p)
    print(proj)

Submission status: Accepted

Solution code:
import math

class Vector:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        
    def norm_2(self):
        return dot(self,self)
    
    def norm(self):
        return math.sqrt(self.norm_2())
    
def v_sum(v1,v2):
    return Vector(v1.x+v2.x,v1.y+v2.y)
def v_diff(v1,v2):
    return Vector(v1.x-v2.x,v1.y-v2.y)
def scalar_multi(k,v):
    return Vector(k*v.x,k*v.y)
    
def dot(vector1,vector2):
    return vector1.x*vector2.x+vector1.y*vector2.y

def cross(vector1,vector2):
    return vector1.x*vector2.y+vector1.y*vector2.x

x1,y1,x2,y2 = map(int,input().split())
p1 = Vector(x1,y1)
p2 = Vector(x2,y2)

d = v_diff(p2,p1)

q = int(input())
for i in range(q):
    x,y = map(int,input().split())
    v = v_diff(Vector(x,y),p1)
    u = v_sum(scalar_multi(dot(v,d)/d.norm_2(),d),p1)
    print('{} {}'.format(round(u.x,9),round(u.y,9)))

Submission status: Accepted

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


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

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

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

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

    def __truediv__(self, sc):
        return Vector(self.x/sc, self.y/sc)

    def __iadd__(self, vec):
        self.x += vec.x
        self.y += vec.y
        return self

    def __isub__(self, vec):
        self.x -= vec.x
        self.y -= vec.y
        return self

    def __imul__(self, sc):
        self.x *= sc
        self.y *= sc
        return self

    def __itruediv__(self, sc):
        self.x /= sc
        self.y /= sc
        return self

    def __str__(self):
        return f'{self.x} {self.y}'

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

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

    def abs(self):
        return (self.x*self.x + self.y*self.y)**0.5


x1, y1, x2, y2 = map(int, input().split())
v1 = Vector(x1, y1)
v2 = Vector(x2, y2)
n = v2-v1
n /= n.abs()

for _ in [0]*int(input()):
    x, y = map(int, input().split())
    v = Vector(x, y) - v1
    print(v1 + n * (n.dot(v)))

Submission status: Accepted

Solution code:
pt = []
x1, y1, x2, y2 = map(int, input().split())
q = int(input())

for _ in range(q):
    xq, yq = map(int, input().split())
    if x2 - x1 == 0:
        pt.append([x1, yq])
    else:
        a1 = (y2-y1)/(x2-x1)
        b1 = y1 - a1*x1
        if a1 == 0:
            pt.append([xq, y1])
        else:
            a2 = -1/a1
            b2 = yq - a2*xq
            x = (b2-b1)/(a1-a2)
            y = a1*x + b1
            pt.append([x, y])

for i in range(q):
    print(pt[i][0], pt[i][1])

Submission status: Accepted

Solution code:
EPS = 10**(-9)
def is_equal(a,b):
    return abs(a-b) < EPS

def norm(v,i):
    import math
    ret = 0
    n = len(v)
    for j in range(n):
        ret += abs(v[j])**i
    return math.pow(ret,1/i)

class Vector(list):
    """
    ベクトルクラス
    対応演算子
    +  : ベクトル和 
    -  : ベクトル差
    *  : スカラー倍、または内積
    ** : 外積
    += : ベクトル和
    -= : ベクトル差
    *= : スカラー倍
    /= : スカラー倍

    メソッド
    self.norm(i) : L{i}ノルムを計算
    """
    def __add__(self,other):
        n = len(self)
        ret = [0]*n
        for i in range(n):
            ret[i] = super().__getitem__(i) + other.__getitem__(i)
        return self.__class__(ret)
    
    def __radd__(self,other):
        n = len(self)
        ret = [0]*n
        for i in range(n):
            ret[i] = other.__getitem__(i) + super().__getitem__(i)
        return self.__class__(ret)
    
    def __iadd__(self, other):
        n = len(self)
        for i in range(n):
            self[i] += other.__getitem__(i)
        return self

    def __sub__(self,others):
        n = len(self) 
        ret = [0]*n
        for i in range(n):
            ret[i] = super().__getitem__(i) - others.__getitem__(i)
        return self.__class__(ret)

    def __iadd__(self, other):
        n = len(self)
        for i in range(n):
            self[i] -= other.__getitem__(i)
        return self

    def __rsub__(self,others):
        n = len(self) 
        ret = [0]*n
        for i in range(n):
            ret[i] = others.__getitem__(i) - super().__getitem__(i)
        return self.__class__(ret)
    
    def __mul__(self,other):
        n = len(self)
        if isinstance(other,list):
            ret = 0
            for i in range(n):
                ret += super().__getitem__(i)*other.__getitem__(i)
            return ret
        else:
            ret = [0]*n
            for i in range(n):
                ret[i] = super().__getitem__(i)*other
            return self.__class__(ret)

    def __rmul__(self,other):
        n = len(self)
        if isinstance(other,list):
            ret = 0
            for i in range(n):
                ret += super().__getitem__(i)*other.__getitem__(i)
            return ret
        else:
            ret = [0]*n
            for i in range(n):
                ret[i] = super().__getitem__(i)*other
            return self.__class__(ret)
    
    
    def __truediv__(self,other):
        """
        ベクトルのスカラー除法
        Vector/scalar
        """
        n = len(self)
        ret = [0]*n
        for i in range(n):
            ret[i] = super().__getitem__(i)/other
        return self.__class__(ret)
    
    def norm(self,i):
        """
        L{i}ノルム
        self.norm(i)
        """
        return norm(self,i)
    
    def __pow__(self,other):
        """
        外積
        self**other
        """
        n = len(self)
        ret = [0]*3
        x = self[:]
        y = other[:]
        if n == 2:
            x.append(0)
            y.append(0)
        if n == 2 or n == 3:
            for i in range(3):
                ret[0],ret[1],ret[2] = x[1]*y[2]-x[2]*y[1],x[2]*y[0]-x[0]*y[2],x[0]*y[1]-x[1]*y[0]
            ret = Vector(ret)
            if n == 2:
                return ret.norm(2)
            else:
                return ret

class Segment:
    def __init__(self,v1,v2):
        self.v1 = v1
        self.v2 = v2

class Line(Segment):
    def get_unit_vec(self):
        return (self.v2-self.v1)/norm(self.v2-self.v1,2)
    
    def projection(self,vector):
        unit_vec = self.get_unit_vec()
        t = unit_vec*(vector-self.v1)
        return self.v1 + t*unit_vec
    
    def is_vertical(self,other):
        return is_equal(0,self.get_unit_vec()*other.get_unit_vec())
    
    def is_horizontal(self,other):
        return is_equal(0,self.get_unit_vec()**other.get_unit_vec())



tmp = list(map(int,input().split()))
p1 = Vector(tmp[:2])
p2 = Vector(tmp[2:])
L = Line(p1,p2)
q = int(input())
for i in range(q):
    p = Vector(map(int,input().split()))
    print(*L.projection(p))

Submission status: Accepted

Solution code:
from decimal import Decimal as D
a,s,d,f=map(D,input().split())
h=[d-a,f-s]
leh=((d-a)**2+(f-s)**2)**(D("0.5"))
for i in range(int(input())):
    x,y=map(D,input().split())
    co=(x-a)*h[0]/leh+(y-s)*h[1]/leh
    print(a+h[0]*co/leh,s+h[1]*co/leh)

Submission status: Accepted

Solution code:
class Vec2:
    def __init__(self, y, x):
        self.y = y
        self.x = x

    def __add__(self, other):
        assert isinstance(other, Vec2)
        return Vec2(self.y+other.y, self.x+other.x)

    def __sub__(self, other):
        assert isinstance(other, Vec2)
        return Vec2(self.y - other.y, self.x - other.x)

    def __mul__(self, other):
        if isinstance(other, Vec2):
            return self.y * other.y + self.x * other.x
        else:
            return Vec2(self.y * other, self.x * other)

    def __str__(self):
        return str((self.y, self.x))

    def size(self):
        return (self.x**2 + self.y**2)**0.5

    def projection(self, vec):
        p = self*vec/self.size()**2
        return self*p


def main():
    x_p1, y_p1, x_p2, y_p2 = map(int, input().split())
    p1 = Vec2(y_p1, x_p1)
    p2 = Vec2(y_p2, x_p2)
    p1p2 = p2-p1
    q = int(input())
    for _ in range(q):
        x_q, y_q = map(int, input().split())
        p1q = Vec2(y_q, x_q) - p1
        p1x = p1p2.projection(p1q)
        x = p1 + p1x
        print(x.x, x.y)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)
    def __mul__(self, other):
        return Point(self.x * other, self.y * other)
    def __floordiv__(self, other):
        return Point(self.x / other, self.y / other)
    def __repr__(self):
        return str(self.x) + ' ' + str(self.y)

class Vector(Point):
    pass

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

def points_to_vector(p1, p2):
    x = p1.x - p2.x
    y = p1.y - p2.y
    return Vector(x, y)

def vector(p):
    return Vector(p.x, p.y)

def dot(v1, v2):
    return v1.x * v2.x + v1.y * v2.y

def cross(v1, v2):
    return v1.x * v2.y - v1.y * v2.x

def norm(v):
    return v.x**2 + v.y**2

def project(s, p):
    base = points_to_vector(s.p1, s.p2)
    hypo = points_to_vector(p, s.p1)
    r = dot(hypo, base) / norm(base)
    return s.p1 + base * r


import sys
# sys.stdin = open('input.txt')

s = list(map(int, input().split()))
p1 = Point(s[0], s[1])
p2 = Point(s[2], s[3])
segment = Segment(p1, p2)

q = int(input())
for i in range(q):
    x, y = map(int, input().split())
    p = Point(x, y)
    ans = project(segment, p)
    print(ans)

Submission status: Accepted

Solution code:
import math

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

    def __add__(self,a):
        return self.__class__(self.x+a.x,self.y+a.y)

    def __sub__(self,a):
        return self.__class__(self.x-a.x,self.y-a.y)

    def __mul__(self,d):
        return self.__class__(self.x*d,self.y*d)

    def __truediv__(self,d):
        return self.__class__(self.x/d,self.y/d)

    def __str__(self):
        return '%.10f %.10f'%(self.x,self.y)

    def abs(self):
        return self.norm()**(1.0/2.0)

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

    def rotate(self,d):
        r = math.pi*d/180.0
        return self.__class__( self.x*math.cos(r)-self.y*math.sin(r),
                               self.x*math.sin(r)+self.y*math.cos(r))

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

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

def reflect(s,p):
    v = s.p2-s.p1
    r = v.dot(p-s.p1)/v.norm()
    return s.p1+v*r

def main():
    a,b,c,d = map(float,input().split())
    s = Segment(Point(a,b),Point(c,d))
    q = int(input())
    for _ in range(q):
        e,f = map(float,input().split())
        p = Point(e,f)
        print (reflect(s,p))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
a,b,c,d=map(float,input().split())
c-=a;d-=b
for _ in [0]*int(input()):
    x,y=map(float,input().split())
    x-=a;y-=b
    z=(c*x+d*y)/(c*c+d*d)
    print(a+c*z,b+d*z)

Submission status: Accepted

Solution code:
import math

EPS = 1e-10

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

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

    def __add__(self, point):
        # + 演算子での挙動を指定
        return Point(self.x+point.x, self.y+point.y)

    def __sub__(self, point):
        # - 演算子での挙動を指定
        return Point(self.x-point.x, self.y-point.y)

    def __mul__(self, a):
        # * 演算子での挙動を指定
        return Point(a*self.x, a*self.y)

    def __truediv__(self, a):
        # / 演算子での挙動を指定
        return Point(self.x/a, self.y/a)

    def __abs__(self):
        # abs関数での挙動を指定
        return math.sqrt(self.norm())

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

    def __eq__(self, point):
        # == 演算子での挙動を指定
        return abs(self.x-point.x) < EPS and abs(self.y-point.y) <EPS

def dot(a, b):
    return a.x*b.x+a.y*b.y

def cross(a, b):
    return a.x*b.y - a.y*b.x

def isOrthogonal(a, b):
    return dot(a, b) == 0

def isParallel(a, b):
    return cross(a, b) == 0

def project(s, p):
    #s: Segment(), p: Point()
    base = s.p2 - s.p1
    r = dot(p-s.p1, base)/base.norm()
    return s.p1+base*r

if __name__ == '__main__':
    from sys import stdin
    input = stdin.readline

    x1, y1, x2, y2 = map(int, input().split())
    s = Segment(Point(x1, y1), Point(x2, y2))

    q = int(input())
    for _ in range(q):
        x0, y0 = map(int, input().split())
        p = Point(x0, y0)
        projection = project(s, p)
        print(projection.x, projection.y)

Submission status: Accepted

Solution code:
from math import pi, cos, sin, atan2
EPS = 10**(-9)

def eq(value1, value2):
    return abs(value1-value2) <= EPS

class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.arg = atan2(y, x) # -PI ~ PI
    
    def __str__(self):
        return "{0:.8f} {1:.8f}".format(self.x, self.y)
    
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)
    
    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)
    
    def __mul__(self, scal):
        return Point(self.x*scal, self.y*scal)
    
    def __truediv__(self, scal):
        return Point(self.x/scal, self.y/scal)
    
    def __eq__(self, other):
        return eq(self.x, other.x) and eq(self.y, other.y)

    # 原点からの距離
    def __abs__(self):
        return (self.x**2+self.y**2)**0.5
    
# 原点を中心にrad角だけ回転した点
def Rotation(vec: Point, rad):
    return Point(vec.x*cos(rad)-vec.y*sin(rad), vec.x*sin(rad)+vec.y*cos(rad))


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


class Line():
    # 点a, bを通る
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self.arg = (a-b).arg % pi
    
    def __str__(self):
        return "[({0}, {1}) - ({2}, {3})]".format(self.a.x, self.a.y, self.b.x, self.b.y)

    # pointを通って平行
    def par(self, point):
        return Line(point, point+(self.a-self.b))

    # pointを通って垂直
    def tan(self, point):
        return Line(point, point + Rotation(self.a-self.b, pi/2))


class Segment(Line):
    def __init__(self, a, b):
        super(Line, self).__init__(a, b)


# 符号付き面積
def cross(vec1: Point, vec2: Point):
    return vec1.x*vec2.y - vec1.y*vec2.x

# 内積
def dot(vec1: Point, vec2: Point):
    return vec1.x*vec2.x + vec1.y*vec2.y

# 点a->b->cの回転方向
def ccw(a, b, c):
    if cross(b-a, c-a) > EPS: return +1 # COUNTER_CLOCKWISE
    if cross(b-a, c-a) < -EPS: return -1 # CLOCKWISE
    if dot(c-a, b-a) < -EPS: return +2 # c -> a -> b
    if abs(b-a) < abs(c-a): return -2 # a -> b -> c
    return 0 # a -> c -> b


# pのlへの射影
def projection(l, p):
    t = dot(l.b-l.a, p-l.a) / abs(l.a-l.b)**2
    return l.a + (l.b-l.a)*t

# pのlによる反射
def reflection(l, p):
    return p + (projection(l, p) - p)*2

def isPararell(l1, l2):
    return eq(cross(l1.a-l1.b, l2.a-l2.b), 0)

def isVertical(l1, l2):
    return eq(dot(l1.a-l1.b, l2.a-l2.b), 0)


def isIntersect_lp(l, p):
    return abs(ccw(l.a, l.b, p)) != 1

def isIntersect_ll(l1, l2):
    return not isPararell(l1, l2) or isIntersect_lp(l1, l2.a)

def isIntersect_sp(s, p):
    return ccw(s.a, s.b, p) == 0

def isIntersect_ss(s1, s2):
    return ccw(s1.a, s1.b, s2.a)*ccw(s1.a, s1.b, s2.b) <= 0 and ccw(s2.a, s2.b, s1.a)*ccw(s2.a, s2.b, s1.b) <= 0

def isIntersect_ls(l, s):
    return cross(l.b - l.a, s.a - l.a) * cross(l.b - l.a, s.b - l.a) < EPS

def isIntersect_cp(c, p):
    return abs(abs(c.p - p) - c.r) < EPS

def isIntersect_cl(c, l):
    return distance_lp(l, c.p) <= c.r + EPS

def isIntersect_cs(c, s):
    pass

def isIntersect_cc(c1, c2):
    pass


def distance_pp(p1, p2):
    return abs(p1-p2)

def distance_lp(l, p):
    return abs(projection(l,p)-p)

def distance_ll(l1, l2):
    return 0 if isIntersect_ll(l1, l2) else distance_lp(l1, l2.a)

def distance_sp(s, p):
    r = projection(s, p)
    if isIntersect_sp(s, r): return abs(r-p)
    return min(abs(s.a-p), abs(s.b-p))

def distance_ss(s1, s2):
    if isIntersect_ss(s1, s2): return 0
    return min([distance_sp(s1, s2.a), distance_sp(s1, s2.b), distance_sp(s2, s1.a), distance_sp(s2, s1.b)])

def distance_ls(l, s):
    if isIntersect_ls(l, s): return 0
    return min(distance_lp(l, s.a), distance_lp(l, s.b))


def crosspoint_ll(l1, l2):
    A = cross(l1.b - l1.a, l2.b - l2.a)
    B = cross(l1.b - l1.a, l1.b - l2.a)
    if eq(abs(A), 0) and eq(abs(B), 0): return l2.a
    return l2.a + (l2.b - l2.a) * B / A

def crosspoint_ss(s1, s2):
    return crosspoint_ll(s1, s2)

def crosspoint_lc(l, c):
    if eq(distance_lp(l, c.p), c.r): return [c.p]
    p = projection(l, c.p)
    e = (l.b - l.a) / abs(l.b-l.a)
    dis = (c.r**2-abs(p-c.p)**2)**0.5
    return [p + e*dis, p - e*dis]

def crosspoint_sc(s, c):
    pass

def crosspoint_cc(c1, c2):
    d = abs(c1.p-c2.p)
    if not abs(c1.r-c2.r) <= d <= c1.r+c2.r:
        return []
    mid_p = (c2.p * (c1.r**2-c2.r**2+d**2) + c1.p * (c2.r**2-c1.r**2+d**2)) / (2*d**2)
    tanvec = Rotation(c1.p-c2.p, pi/2)
    return crosspoint_lc(Line(mid_p, mid_p+tanvec), c1)


# pからのcの接点
def tangent_cp(c, p):
    return crosspoint_cc(c, Circle(p, (abs(p-c.p)**2 - c.r**2)**0.5))





import sys
input = sys.stdin.readline

def verify_1A():
    p1x, p1y, p2x, p2y = map(int, input().split())
    l = Line(Point(p1x, p1y), Point(p2x, p2y))
    Q = int(input())
    Query = [list(map(int, input().split())) for _ in range(Q)]
    for px, py in Query:
        p = Point(px, py)
        print(projection(l, p))

verify_1A()

Submission status: Accepted

Solution code:
def project(x,y):
    base=[x2-x1,y2-y1]
    hypo=[x-x1,y-y1]
    r=(base[0]*hypo[0]+base[1]*hypo[1])/(base[0]**2+base[1]**2)
    return x1+base[0]*r,y1+base[1]*r


x1,y1,x2,y2=map(int,input().split())
q=int(input())
for i in range(q):
    x,y=map(int,input().split())
    print(*project(x,y))

Submission status: Accepted

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

x1, y1, x2, y2 = map(int, input().split())
p1=x1+y1*1j
p2=x2+y2*1j
l=p2-p1
l_norm=dot(l,l)         #lの大きさの２乗を計算
q=int(input())

for x3, y3 in (map(int, input().split()) for _ in [0]*q):
    p3=x3+y3*1j
    a=p3-p1
    k=dot(a,l)/l_norm
    projection_vector=k*l
    print(x1+projection_vector.real,y1+projection_vector.imag)

Submission status: Accepted

Solution code:
def projection(x1, y1, x2, y2, x0, y0):
    if x2 == x1:
        return (x2, y0)
    m = float(y2 - y1) / float(x2 - x1)
    b = y1 - m * x1 # intercept of the original line                                                                                             
    xp = (x0 + (m * y0) - (m * b)) / (1. + (m * m))
    yp = ((m * x0) + ((m * m) * y0) + b) / (1. + (m * m))
    return (xp, yp)

x1, y1, x2, y2 = map(float, input().split())
q = int(input())
for _ in range(q):
    x0, y0 = map(float, input().split())
    ans = projection(x1, y1, x2, y2, x0, y0)
    print(ans[0], ans[1])

Submission status: Accepted

Solution code:
EPS = 0.0000000001

class Point:
    
    global EPS
    
    def __init__(self, x = 0, y = 0):
        self.x = x
        self.y = y
        
        
    def __add__(a, b):
        s = a.x + b.x
        t = a.y + b.y
        return Point(s, t)
        
    def __sub__(a, b):
        s = a.x - b.x
        t = a.y - b.y
        return Point(s, t)
            
    def __mul__(self, a):
        s = a * self.x
        t = a * self.y
        return Point(s, t)
        
    def __truediv__(self, a):
        s = self.x / a
        t = self.y / a
        return Point(s, t)
            
            
            
            
    def norm(self):
        return self.x * self.x + self.y * self.y
        
    def abs(self):
        return self.norm() ** 0.5
            
    
            
            
    def __eq__(self, other):
        return abs(self.x - other.y) < self.EPS and abs(self.y - other.y) < self.EPS
            
            
            
    def dot(self, b):
        return self.x * b.x + self.y * b.y
        
    def cross(self, b):
        return self.x * b.y - self.y * b.x
    
    
class Segment:
    def __init__(self, p1, p2):
        self.p1 = p1
        self.p2 = p2

def project(s, p):
    base = s.p2 - s.p1
    hypo = p - s.p1
    r = hypo.dot(base) / base.norm()
    return s.p1 + base * r



nums=list(map(int,input().split()))
s = Segment(Point(nums[0], nums[1]), Point(nums[2], nums[3]))

n = int(input())
for i in range(n):
    nums=list(map(int,input().split()))
    p = Point(nums[0], nums[1])
    x = project(s, p)
    print(x.x, x.y)