洛谷P3602 Koishi Loves Segments(貪心,multiset)

洛谷題目傳送門

貪心小水題。

把線段按左端點從小到大排序,限制點也是從小到大排序,然後一起掃一遍。

對於每一個限制點實時維護覆蓋它的所有線段,如果超過限制,則貪心地把右端點最大的線段永遠刪去,不計入答案。顯然這樣做對後面的決策更有利。

以右端點爲鍵值,需要資瓷動態插入,刪除最小值、最大值,multiset就行了。

代碼很短,常數應該比較大,但不知爲何暫時混了個rk1。

#include<bits/stdc++.h>
#define R register int
#define G if(++ip==ie)if(fread(ip=buf,1,SZ,stdin))
using namespace std;
const int SZ=1<<19,N=4e5+9;
char buf[SZ],*ie=buf+SZ,*ip=ie-1;
inline int in(){
	G;while(*ip<'-')G;
	R f=*ip=='-';if(f)G;
	R x=*ip&15;G;
	while(*ip>'-'){x*=10;x+=*ip&15;G;}
	return f?-x:x;
}
struct Seg{
	int x,y;
	inline bool operator<(const Seg&a)const{
		return x<a.x;
	}
}a[N],b[N];
multiset<int>s;
int main(){
	R n=in(),m=in(),ans=n;
	for(R i=0;i<n;++i)a[i].x=in(),a[i].y=in();
	for(R i=0;i<m;++i)b[i].x=in(),b[i].y=in();
	sort(a,a+n);sort(b,b+m);
	for(R i=0,j=0;i<m;++i){
		while(j<n&&a[j].x<=b[i].x)s.insert(a[j++].y);
		while(s.size()&&*s.begin()<b[i].x)s.erase(s.begin());
		while(s.size()>b[i].y)s.erase(--s.end()),--ans;
	}
	return cout<<ans<<endl,0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章