[Programming Question] The "biggest" point collection

Problem:
P is a given set of two-dimensional plane integer points. Define a point x in P. If x satisfies that any point in P is not in the upper right area of ​​x (both horizontal and vertical coordinates are greater than x), it is called the "maximum". Find the set of all "largest" points. (The abscissa and ordinate of all points are not repeated, and the coordinate axis range is within [0, 1e9))

As shown in the figure below: the solid points are the set of points that meet the conditions. Please implement the code to find the set of all the "maximum" points in the set P and output it.
Insert picture description here
Enter a description:

第一行输入点集的个数 N, 接下来 N 行,每行两个数字代表点的 X 轴和 Y 轴。
对于 50%的数据,  1 <= N <= 10000;
对于 100%的数据, 1 <= N <= 500000;

Output description:

输出“最大的” 点集合, 按照 X 轴从小到大的方式输出,每行两个数字分别代表点的 X 轴和 Y轴。

Example:

输入
5
1 2
5 3
4 6
7 5
9 0
输出
4 6
7 5
9 0

Analysis
The key point of this question is to perceive:
1. Scan from top to bottom, all the points that meet the requirements are x-coordinates greater than the x-coordinate value of the last qualified point;
2. Scan from right to left to meet the requirements The y coordinate is greater than the y coordinate of the last matching point;

Therefore, we can sort the point set according to the size of the y axis (the first method is convenient for direct output), save the x coordinate of the current point with an integer value, and compare the two x when scanning to the next point The size of the coordinate value, if it is larger, it belongs to the target point set for output.

Code:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

//建立点类
class Point
{
    
    
public:
	int x, y;
	Point(int x,int y):x(x),y(y){
    
    }
};
//制作sort()第三参数,使数组能按照y轴数值由大到小排列
bool cmp(const Point &A,const Point &B)
{
    
    
	return A.y > B.y;
}

int main()
{
    
    
	int n, x, y;
	vector<Point> arr;
	cin >> n;
	//输入数据
	for(int i=0;i<n;i++)
	{
    
    
		cin >> x >> y;
		arr.push_back(Point(x, y));
	}
	//排序
	sort(arr.begin(), arr.end(), cmp);
	//制定一个用于比较的数值
	int compare = -1;
	for(int i=0;i<n;i++)
	{
    
    
		//若比较的点的x轴坐标值大于当前的比较值
		if(arr[i].x>compare)
		{
    
    
			//输出,并更新比较值
			cout << arr[i].x << " " << arr[i].y << endl;
			compare = arr[i].x;
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_43530773/article/details/115009081