給定n個區間,要求選出若干個來完整地覆蓋0~T
輸入使用區間最小的數目
貪心思想:每次選擇可以覆蓋到“開頭”且右邊界最靠右的點
編寫方法:加上排序和邊界修正可較小編寫代碼的難度
貪心思想的證明:
假設選取了區間a1, a2, a3, a4, a5,a6來完成覆蓋任務
另有區間b可以覆蓋到a3的“開頭”且右邊界比a3靠右,則可以將a3替換爲b,不會增加區間數量。
#include <stdio.h>
#include <algorithm>
#define MAREA 25010
using namespace std;
struct aa
{
int l;
int r;
};
aa area[MAREA];
bool cmp(const aa &a, const aa &b)
{
return a.l < b.l;
}
int main()
{
int num_cow, T;
int res = 0;
scanf("%d %d", &num_cow, &T);
for (int i = 0; i < num_cow; ++i)
scanf("%d %d", &area[i].l, &area[i].r);
sort(area, area+num_cow, cmp);
int now = 0;
int beg = 1;
while(beg <= T && now < num_cow)
{
int temp = -1;
while(now < num_cow && area[now].l <= beg)
{
if(temp < area[now].r)
temp = area[now].r;
now++;
}
if(temp == -1)
break;
else
{
beg = temp+1;
res++;
}
}
if(beg>T)
printf("%d\n", res);
else
printf("-1\n");
}