跳到正文

个人记录

贪心总结

txa130729约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年8月14日
收录
2026年8月14日
更新
2026年11月15日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

点覆盖区间

题意

给定若干区间,选最少数量的点,使得每个区间至少包含一个选中的点。(种树问题)

策略

将所有区间按右端点从小到大排序

选第一个区间的右端点作为选中的点

往后遍历,如果当前区间已经包含这个点就跳过;否则选取它的右端点。

最大不相交区间

题意

选出尽可能多的区间,任意两个区间不能相交(会议问题)

策略

将区间按右端点从小到大排序

维护上一个选中区间的右端 last

如果当前区间左端点>=last,就选这个区间,更新last=当前右端。

区间覆盖

题意

给定目标区间[l,r]和一些可小区间,选择最少数量的区间完整覆盖[l,r]。(值班问题)

策略

将区间按左端点从小到大排序

当前已经覆盖到now,需要覆盖到r

在所有左端点<=now的区间中,挑选右端最大的那一个,计数+1,now更新为这个最大右端,直到now>=r,如果找不到能延伸的区间,说明无解。

例题

P1496 火烧赤壁

C++
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
struct node{
	ll l,r;
}a[1000001];
ll n;
bool cmp(node x,node y){
	if(x.l==y.l) return x.r<y.r;
	return x.l<y.l;
}
int main(){
	cin>>n;
	for(ll i=1;i<=n;i++) cin>>a[i].l>>a[i].r;
	sort(a+1,a+1+n,cmp);
	ll x=a[1].l,y=a[1].r,ans=y-x;
	for(ll i=2;i<=n;i++)
		if(a[i].l<=y){
			if(a[i].r>y) ans+=a[i].r-y,y=a[i].r;
		}
		else x=a[i].l,y=a[i].r,ans+=y-x;
	cout<<ans;
	return 0;
}

P2207 [USACO13OPEN] Photo B

C++
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
struct node{
	ll l,r;
}a[1000001];
ll n,m;
bool cmp(node x,node y){
	if(x.r==y.r) return x.l<y.l;
	return x.r<y.r;
}
int main(){
	cin>>n>>m;
	for(ll i=1;i<=m;i++){
		cin>>a[i].l>>a[i].r;
		if(a[i].l>a[i].r) swap(a[i].l,a[i].r);
	}
	sort(a+1,a+1+m,cmp);
	ll t=a[1].r-1,ans=1;
	for(ll i=2;i<=m;i++)
		if(a[i].l>t) t=a[i].r-1,ans++;
	cout<<ans+1;
	return 0;
}

T804056 线段

C++
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
struct node{
	ll l,r;
}a[1000001];
ll n;
vector<ll>ans;
bool cmp(node x,node y){
	return x.r<y.r;
}
int main(){
	cin>>n;
	for(ll i=1;i<=n;i++){
		cin>>a[i].l>>a[i].r;
		if(a[i].l>a[i].r) swap(a[i].l,a[i].r);
	}
	sort(a+1,a+1+n,cmp);
	ll t=a[1].r;
    ans.push_back(t);
	for(ll i=2;i<=n;i++)
        if(a[i].l>t) ans.push_back(a[i].r),t=a[i].r;
	cout<<ans.size()<<'\n';
	for(ll i=0;i<ans.size();i++) cout<<ans[i]<<' ';
	return 0;
}

P1325 [ICPC 2002 Beijing R] 雷达安装

C++
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
struct node{
	double l,r;
}a[100001];
bool cmp(node x,node y){
	return x.r<y.r;
}
ll n,d;
int main(){
	cin>>n>>d;
	for(ll i=1;i<=n;i++){
		double x,y,t;
		cin>>x>>y;
		if(d*d-y*y<0){
			cout<<-1;
			return 0;
		}
		t=sqrt(d*d*1.0-y*y);
		a[i].l=x-t,a[i].r=x+t;
	}
	sort(a+1,a+1+n,cmp);
	double t=a[1].r;
	ll ans=0;
	for(ll i=2;i<=n;i++)
		if(a[i].l<=t) continue;
		else t=a[i].r,ans++;
	cout<<ans+1;
	return 0;
}
原文