[CF22D] Segments

[CF22D] Segments - 贪心

Description

坐标轴上 n 条线段,找出 k 个点,使得 n 条线段都至少有一个点在上面。求 k 的最小值并构造方案。

Solution

按右端点排序,维护一个当前最远点,如果新进来的左端点在最远点右边,就开新线段,并将最远点设置为该线段的右端点

#include <bits/stdc++.h>
using namespace std;

signed main()
{
    int n, pos = -1e9;
    vector<pair<int, int>> segs;
    vector<int> ans;
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        int x, y;
        cin >> x >> y;
        if (x > y)
            swap(x, y);
        segs.push_back({y, x});
    }
    sort(segs.begin(), segs.end());
    for (int i = 0; i < n; i++)
    {
        auto [r, l] = segs[i];
        if (l > pos)
        {
            pos = r;
            ans.push_back(pos);
        }
    }
    cout << ans.size() << endl;
    for (auto i : ans)
        cout << i << " ";
}
原文地址:https://www.cnblogs.com/mollnn/p/14410707.html