Step1 Problem:
给你一系列闭合区间(以0 0结束),求[0,M]至少需要几个区间可以将其包含,输出区间个数 和 区间(按左边界从小到大)。
数据范围:
1<= M <=5000, -50000 <= Li < Ri <= 50000.
Step2 Involving algorithms:
贪心
Step3 Ideas:
假设我们要包含,[0,0]这个区间,需要的区间左边界肯定得<=0,右边界越大越好。
右边界大的 效果一定比 右边界小的好,因为作用域大。
对于[0,0]这个区间,例如[-2, 1] 和 [-1, 2]这个两个区间作用域分别为[0, 1], [0, 2],右区间大的 作用域大。
所以一开始[0,0]我们找到满足的右边界最大lmax后,[0,0]更新为[lmax, lmax]继续查找就好了。
Step4 Code:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
struct node
{
int lt, rt;
bool operator < (const node &b) const {
if(lt == b.lt) return rt < b.rt;
else return lt < b.lt;
}
};
node a[N];
int ans[N];
int main()
{
int pos, u, v;
scanf("%d", &pos);
int top = 0;
while(~scanf("%d %d", &u, &v))
{
if(!u && !v) break;
if(v <= 0 || u > pos) continue;
a[top++] = (node){u, v};
}
sort(a, a + top);
int lpos = 0, top1 = 0;
for(int i = 0; lpos < pos && i < top; )
{
int Max = lpos, ma;
if(a[i].lt > lpos) break;
while(a[i].lt <= lpos && i < top)
{
if(Max < a[i].rt) {
Max = a[i].rt;
ma = i;
}
i++;
}
if(Max != lpos) {
lpos = Max;
ans[top1++] = ma;
}
}
// printf("%d\n", top1);
if(lpos < pos) {
printf("No solution\n");
} else {
printf("%d\n", top1);
for(int i = 0; i < top1; i++)
printf("%d %d\n", a[ans[i]].lt, a[ans[i]].rt);
}
return 0;
}