Problems
In two dimensions, the coordinates of all integer points are represented as ordered pairs in the form of (x, y).
How should we create many such points?
We could make a structure containing two int variables, but we can also manage them using the pair data type that we will learn about this time.
The pair data type is in the #include <utility> header. Let’s also use using namespace std;
(The utility header is often included inside <algorithm>, so adding only the <algorithm> header also works.)
It is declared as pair<data type, data type>.
If it is like the coordinates of an integer point (integer, integer), it would be pair<int, int>.
If you want an ordered pair of (string, integer), you declare it as pair<string, int>.
There are several ways to declare a pair and assign values to it, as shown below.
pair<int, int> a;
a = {2, 5}; // ①
a = make_pair(2, 5); // ②
a.first = 2;
a.second = 5; // ③Like method 1, you can assign values by enclosing them in braces,
or like method 2, you can use the make_pair function,
or like method 3, you can assign values to each element separately.
Here, the first element becomes (pair variable name).first, and the second element becomes (pair variable name).second. This is syntax, so you need to memorize it.
What happens if we sort a data structure containing multiple pairs?
Unless we explicitly set a different sorting standard,
it is designed to sort based on the first (front element) by default,
and among those with the same first (front element) value, it sorts based on the second (back element).
Now let’s solve a simple practice problem that applies this.
Input
On the first line, the number of integer points N is given. (1 ≤ N ≤ 100,000)
On the second line, the x-coordinates and y-coordinates of the N points are given. (All are natural numbers less than or equal to 10,000)
Output
Sort these points in ascending order based on their x-coordinates, and among the points with the same x-coordinate, sort them in ascending order based on their y-coordinates.
Then, in the sorted order, output (the product of the x-coordinate and y-coordinate) over N lines.
For the sake of improving your skills, be sure to implement this using the pair data type!
Example
5
9 3
1 8
1 4
1 5
2 3
4
5
8
6
27
After sort the points:
(1, 4)
(1, 5)
(1, 8)
(2, 3)
(9, 3)
After that, you just need to find the product of the x-coordinate and y-coordinate for each point and print it out.