### 思路
1. **输入处理**:读取区间数和每个区间的端点。
2. **排序区间**:按照区间的右端点进行排序。
3. **选择区间**:使用贪心算法选择不相交的区间,尽可能多地选择区间。
4. **计算结果**:计算需要去掉的区间数。
### 细节
- **排序**:将所有区间按照右端点从小到大排序。
- **贪心选择**��从左到右遍历区间,选择不与前一个选择的区间相交的区间。
- **计算去掉的区间数**:总区间数减去选择的区间数。
### 伪代码
```plaintext
function min_intervals_to_remove(n, intervals):
sort intervals by end point
count = 0
end = -infinity
for each interval in intervals:
if interval.start >= end:
end = interval.end
else:
count += 1
return count
```
### C++代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int min_intervals_to_remove(int n, vector<pair<int, int>>& intervals) {
// Sort intervals by their end points
sort(intervals.begin(), intervals.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.second < b.second;
});
int count = 0;
int end = -1000000000; // Use a large negative number instead of INT_MIN
for (const auto& interval : intervals) {
if (interval.first >= end) {
end = interval.second;
} else {
count += 1;
}
}
return count;
}
int main() {
int n;
cin >> n;
vector<pair<int, int>> intervals(n);
for (int i = 0; i < n; ++i) {
cin >> intervals[i].first >> intervals[i].second;
}
cout << min_intervals_to_remove(n, intervals) << endl;
return 0;
}
标签:count,优先,end,8602,interval,相交,int,intervals,区间
From: https://blog.csdn.net/huang1xiao1sheng/article/details/141602015