-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathmain.cpp
91 lines (72 loc) · 2.12 KB
/
main.cpp
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <bits/stdc++.h>
using namespace std; // NOLINT
//
// Represents an inclusive range of integers in [lo, hi].
//
struct range {
int lo;
int hi;
int i;
int size() {
return hi - lo + 1;
}
//
// Order by lo and break ties with hi.
//
bool operator<(const range& other) const {
if (lo < other.lo) {
return true;
} else if (lo > other.lo) {
return false;
}
return hi < other.hi;
}
};
int main() {
size_t n, k;
cin >> n >> k;
vector<range> coupons(n);
for (size_t i = 0; i < n; i++) {
cin >> coupons[i].lo >> coupons[i].hi;
coupons[i].i = i + 1;
}
// Sort the coupons by lower bound.
sort(coupons.begin(), coupons.end());
// The range of product ID's that our best choices of k coupons can cover.
range biggest {0, -1};
// Holds upper bounds of current coupon set. Lowest upper bound is at top.
priority_queue<int, vector<int>, greater<int>> upper;
for (const range& coupon : coupons) {
upper.push(coupon.hi);
// If we have k coupons selected -> 1) Check if the range of the current
// set is wider than the current best and 2) Pop off the lowest upper bound
// so that we can potentially replace it with a higher upper bound.
if (upper.size() == k) {
// coupon.lo is the lower bound of the current range since we sorted by
// lo and coupon.lo >= other.lo for all other coupons in the current set.
range candidate {coupon.lo, upper.top()};
if (candidate.size() > biggest.size()) {
biggest = candidate;
}
upper.pop();
}
}
cout << biggest.size() << endl;
if (biggest.size() == 0) {
// There are not k coupons that overlap at all so we can select any k and
// we are guaranteed that at least 2 in our selection will not overlap.
for (size_t i = 1; i <= k; i++) {
cout << i << " ";
}
} else {
// Select k coupons that completely fit the best range.
for (size_t i = 0; i < n && k > 0; i++) {
if (coupons[i].lo <= biggest.lo && coupons[i].hi >= biggest.hi) {
cout << coupons[i].i << " ";
k--;
}
}
}
cout << endl;
return 0;
}