笔试刷题-头条2018-07-09

2018-07-09  本文已影响0人  Dodo159753

题目描述:

/**
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
*/

思路如下:

题目特点:所有点中不存在两个点横坐标相同或者纵坐标相同
让点按x升序排列,然后遍历同时维护一个以y为降序的堆

代码如下:

#include<stdio.h>
#include<iostream>
#include<stack>
#include<algorithm>
#include<vector>
 
#define MAX_N 500005
 
using namespace std;
 
struct Node{
    int x=0, y=0;
    Node(){}
    Node(int x, int y){
        this->x=x;
        this->y=y;
    }
    Node(const Node &node){
        this->x=node.x;
        this->y=node.y;
    }
};
 
bool NodeCmpByX(const Node &n1, const Node &n2){
    return n1.x<n2.x;
}
 
Node nodes[MAX_N];
 
int main()
{
    int N;
    scanf("%d", &N);
    for(int i=0; i<N; i++){
        int x, y;
        scanf("%d%d", &x, &y);
        nodes[i]=Node(x, y);
    }
    sort(nodes, nodes+N, NodeCmpByX);
    stack<Node> st;
    for(int i=0; i<N; i++){
        if(st.empty() || st.top().y>nodes[i].y){
            st.push(nodes[i]);
        }
        else{
            while(!st.empty() && st.top().y<=nodes[i].y)
                st.pop();
            st.push(nodes[i]);
        }
    }
    vector<Node> result;
    while(!st.empty()){
        result.push_back(st.top());
        st.pop();
    }
    for(int i=result.size()-1; i>=0; i--)
        printf("%d %d\n", result[i].x, result[i].y);
    return 0;
}

上一篇 下一篇

猜你喜欢

热点阅读