CSP: 称检测点查询

称检测点查询

原题链接

涉及的知识点:

  1. 优先队列

满分代码如下:

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;

//为优先队列自定义的比较函数
static bool cmp(pair<int, vector<int>>& m, pair<int, vector<int>>& n) {
    if (m.first == n.first) {
        return m.second[0] < n.second[0];
    }
    else {
        return m.first < n.first;
    }
}

int main()
{
    int n, X, Y;
    int x, y;
    // 定义一个大顶堆,当堆中的元素个数小于3时直接压入;等于3时,只需比较对顶的元素和当前元素即可因为其他元素必定更小
    priority_queue<pair<int, vector<int>>, vector<pair<int, vector<int>>>, decltype(&cmp)> q(cmp);

    scanf("%d%d%d", &n, &X, &Y);
    for (int i = 0; i < n; ++i) {
        scanf("%d%d", &x, &y);
        int D = (x - X) * (x - X) + (y - Y) * (y - Y);
        vector<int> temp;
        temp.push_back(i);
        temp.push_back(x);
        temp.push_back(y);

        if (q.size() < 3) {
            q.emplace(D, temp);
        }
        else {
            pair<int, vector<int>> t = q.top();
            if (D < t.first || (D == t.first && i < t.second[0])) {
                q.pop();
                q.emplace(D, temp);
            }
        }
    }

    stack<int> st;
    // 题目要求从小到大输出,故要将对堆中的元素放入栈中再输出
    while (!q.empty()) {
        pair<int, vector<int>> t = q.top();
        q.pop();
        st.emplace(t.second[0]);
    }
    while (!st.empty()) {
        printf("%d\n", st.top() + 1);
        st.pop();
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值