参考
- 贪心算法——有关区间的问题
- 刘汝佳《算法竞赛入门经典·第2版》第8.4节 贪心法(P231)
区间完全覆盖问题
贪心策略:先按左界排序,然后每次都选择左界在当前覆盖范围内,右界相对最大的区间,并更新覆盖范围。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1005;
typedef pair<int, int> P;
P a[maxn];
void solve(int n)
{
int cnt = 0;
sort(a, a+n);
int maxb = a[n-1].second, cover = a[0].first, index = 0;
while (cover < maxb)
{
int nowMax = 0;
//找到当前能覆盖的,且右界最大的区间
while(index < n)
{
if (a[index].first > cover) break;
if (a[index].first <= cover)
{
if (a[index].second > nowMax)
nowMax = a[index].second;
}
index++;
}
//延伸右界
cover = nowMax;
cnt++;
}
cout << cnt << endl;
}
int main()
{
//freopen("./input.txt", "r", stdin);
int n;
cin >> n;
for (int i = 0; i<n; ++i)
scanf("%d,%d", &a[i].first, &a[i].second);
solve(n);
}