#K3536. K Closest Points to the Origin
K Closest Points to the Origin
K Closest Points to the Origin
Given a set of N points in the 2D plane and an integer K, your task is to find the K points that are closest to the origin (0, 0).
The distance from a point \((x,y)\) to the origin is given by the Euclidean distance formula:
\(\sqrt{x^2 + y^2}\)
In this problem, you are required to compute the distance for each point and output the K points with the smallest distances. If two points have the same distance, they should appear in the order they appear in the input.
The input will be read from standard input (stdin) and the output should be written to standard output (stdout). Each point should be output on its own line in the format: x y
.
inputFormat
The input is given via standard input (stdin) and has the following format:
- The first line contains two integers N (the number of points) and K (the number of closest points to output), separated by a space.
- Each of the next N lines contains two integers representing the coordinates
x
andy
of a point, separated by a space.
outputFormat
Print exactly K lines to standard output (stdout). Each line should contain two integers x
and y
representing one of the K closest points. The points should be printed in the order of increasing distance from the origin. In case of ties, maintain the order of appearance from the input.
2 1
1 3
-2 2
-2 2
</p>