給定 N 個閉區間 [L, R],選取最少數量的點,使每個區間至少包含一個選取的點。輸出最少點數。
R 升序排序 (R 相同按 L 降序)。ans = 0, last_selected = -∞。last_selected < L (當前點不覆蓋該區間),則選取 R 作為新點:last_selected = R, ans++。#includeusing namespace std; struct Interval { int l, r; }; int main() { int n; while (scanf("%d", &n) == 1) { vector a(n); for (int i = 0; i < n; i++) { int x, y; scanf("%d%d", &x, &y); a[i].l = min(x, y); a[i].r = max(x, y); } sort(a.begin(), a.end(), [](const Interval& A, const Interval& B) { return A.r != B.r ? A.r < B.r : A.l > B.l; }); int ans = 0; int last = -1e9; for (auto& seg : a) { if (last < seg.l) { last = seg.r; ans++; } } printf("%d\n", ans); } return 0; }
Input: 4 1 5 2 4 1 4 2 3 3 1 2 3 4 5 6 1 2 Output: 1 3 1
第一組:區間 [2,3] 最早結束,選 3 覆蓋所有。
第二組:三個不相交區間,各需一點。
第三組:單區間需 1 點。
last 即可。