The input consists of N points in a two-dimensional plane. You need to sort these points based on their x-coordinates as the primary key and their y-coordinates as the secondary key, in ascending order.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
The first line of input should contain a positive integer N, indicating the number of points. Following that, there will be N lines. Each line will consist of two positive integers x[i] and y[i], separated by a space, representing the coordinates of the i-th point as (x[i], y[i]). | Output N lines, where each line represents the coordinates of the i-th point after sorting. |
4 2 4 1 2 3 4 2 3 | 1 2 2 3 2 4 3 4 |
Thought Process
Store the coordinates in a pair and then store these pairs in an array or vector. After sorting them using sort, iterate through the array or vector using a for loop to output the coordinates sequentially.
Sample Code-ZeroJudge A915: 2D Point Sorting
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
int N;
cin >> N;
vector<pair<int, int>>v;
for (int i = 0; i<N; i++)
{
int x, y;
cin >> x >> y;
pair<int, int> axis;
axis.first = x;
axis.second = y;
v.push_back(axis);
}
sort(v.begin(), v.end());
for (int i = 0; i<N; i++)
{
cout << v[i].first << " " << v[i].second << "\n";
}
}
//ZeroJudge A915
//Dr. SeanXD