給定 N 條線段 (起點 S, 終點 E),選出最多條件為兩兩不重疊的線段數量。N ≤ 10000,座標範圍 ±1e9。
「優先選擇終點最早的線段,再從剩餘中繼續選擇終點最早且起點 ≥ 上一條終點的線段」可得到最優解。
證明核心:交換論證。任何最優解若第一條線段非最早結束,可替換為最早結束者而不減少總數。
排序 `O(N log N)`,掃描 `O(N)`,總 `O(N log N)`,滿足 N=10000。
#include <bits/stdc++.h>
using namespace std;
struct Seg { long long s, e; };
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N;
while (cin >> N) {
vector a(N);
for (int i = 0; i < N; ++i) cin >> a[i].s >> a[i].e;
sort(a.begin(), a.end(), [](const Seg& x, const Seg& y) {
return x.e < y.e || (x.e == y.e && x.s < y.s);
});
int ans = 0;
long long last = LLONG_MIN;
for (const auto& seg : a) {
if (seg.s >= last) {
++ans;
last = seg.e;
}
}
cout << ans << '\n';
}
return 0;
}