2018今日头条

P为给定的二维平面整数点集。定义 P 中某点x,如果x满足 P 中任意点都不在 x 的右上方区域内(横纵坐标都大于x),则称其为“最大的”。求出所有“最大的”点的集合。(所有点的横坐标和纵坐标都不重复, 坐标轴范围在[0, 1e9) 内)

如下图:实心点为满足条件的点的集合。请实现代码找到集合 P 中的所有 ”最大“ 点的集合并输出。

输入描述:
第一行输入点集的个数 N, 接下来 N 行,每行两个数字代表点的 X 轴和 Y 轴。
对于 50%的数据,  1 <= N <= 10000;
对于 100%的数据, 1 <= N <= 500000;
输出描述:
输出“最大的” 点集合, 按照 X 轴从小到大的方式输出,每行两个数字分别代表点的 X 轴和 Y轴。
输入例子1:
5
1 2
5 3
4 6
7 5
9 0
输出例子1:
4 6
7 5
9 0
#include<bits/stdc++.h>
using namespace std;

bool cmpFirst(const pair<int,int>&x,const pair<int,int>&y){
    return x.first>y.first;
}

int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        vector<pair<int,int>> arr;
        vector<int> tmpArr;
        for(int i=0,x,y;i<n;i++){
            scanf("%d%d",&x,&y),arr.emplace_back(x,y),tmpArr.push_back(y);
        }
        sort(arr.begin(),arr.end(),cmpFirst);
        
        int y_max=-1;
        vector<pair<int,int>> ans;
        for(int i=0;i<n;i++){
            if(arr[i].second>y_max){
                y_max=arr[i].second;
                ans.push_back(arr[i]);
            } 
        }
        for(auto it =ans.rbegin();it!=ans.rend();it++){
            printf("%d %d
",it->first,it->second);
        }
    }
    return 0;
}

python 代码:根据上面的思路写的 但是只通过了80%(内存超出限制)

n=int(input())
points=[]
res=[]
for i in range(n):
    [x,y]=list(map(int,input().split()))
    points.append((x,y))
points.sort(reverse=True)#sorted(points)
maxY=-1;
for p in points:
    if p[1]>maxY:
        maxY=p[1]
        res.append(p)
for p in res[::-1]:
    print(p[0],p[1])
原文地址:https://www.cnblogs.com/bright-mark/p/9464145.html