summaryrefslogtreecommitdiffstats
path: root/01-algorithmic_toolbox/02-greedy_algorithms/04-covering_segments/covering_segments.cpp
blob: 9067dfebea6589a043a986f087d74c6f033704f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <algorithm>
#include <iostream>
#include <climits>
#include <vector>

using std::vector;

struct Segment {
  int start, end;
};

bool _sort(Segment i, Segment j)
{
    return (i.end <= j.end);
}

vector<int> optimal_points(vector<Segment> &segments)
{
    vector<int> points;

    std::sort(segments.begin(), segments.end(), _sort);

    while (segments.size() > 0) {
        int v = segments.at(0).end;
        segments.erase(segments.begin());
        points.push_back(v);

        for (std::vector<Segment>::iterator it = segments.begin() ; it != segments.end(); ) {
            if (it->start <= v && it->end >= v) {
                segments.erase(it);
            } else
                it++;
        }
    }

    return points;
}

int main() {
  int n;
  std::cin >> n;
  vector<Segment> segments(n);
  for (size_t i = 0; i < segments.size(); ++i) {
    std::cin >> segments[i].start >> segments[i].end;
  }
  vector<int> points = optimal_points(segments);
  std::cout << points.size() << "\n";
  for (size_t i = 0; i < points.size(); ++i) {
    std::cout << points[i] << " ";
  }
  std::cout << '\n';
}