P1868 饥饿的奶牛

Jennie

转移的时候要知道区间最值

那何不利用线段树来解决

\(O(nlogn)\)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
template<class T>
void read(T &now){
	now=0;
	char c=getchar();
	int f=1;
	while((!isdigit(c))){
		if(c=='-') f=-1;
	//	cout<<isdigit(c)<<" "<<c<<" ";
		c=getchar();
	}
	while(isdigit(c)){
		now=(now<<1)+(now<<3)+c-'0';
		c=getchar();
	}
	now*=f;
}
int tr[24000101];
int f[5050005];
int n;
struct se{
	int l;
	int r;
	friend bool operator <(se x,se y){
		return x.r==y.r?x.l<y.l:x.r<y.r;
	}
}sec[5000005];
void pushup(int ro){
	tr[ro]=max(tr[ro<<1],tr[ro<<1|1]);
}
void add(int ro,int l,int r,int L,int R,int k){
	if(L<=l&&r<=R){
		tr[ro]=k;
		return ;
	}
	int mid=(l+r)>>1;
	if(L<=mid) add(ro<<1,l,mid,L,R,k);
	if(R>mid) add(ro<<1|1,mid+1,r,L,R,k);
	pushup(ro); 
}
int que(int ro,int l,int r,int L,int R){
	if(L<=l&&r<=R){
		return tr[ro];
	}
	int mid=(l+r)>>1;
	int ans=0;
	if(L<=mid)  ans=max(que(ro<<1,l,mid,L,R),ans);
	if(R>mid) ans=max(que(ro<<1|1,mid+1,r,L,R),ans);
	return ans;
}
int rr;
int main(){
	read(n);
	for(int i=1;i<=n;++i){
		read(sec[i].l);read(sec[i].r);
		sec[i].l+=2;
		sec[i].r+=2;
		rr=max(sec[i].r,rr);
	}
	sort(sec+1,sec+1+n);
	for(int i=1;i<=n;++i){
		f[sec[i].r]=max(que(1,1,rr,1,sec[i].l-1)+sec[i].r-sec[i].l+1,que(1,1,rr,sec[i].l,sec[i].r));
		//cout<<que(1,1,rr,sec[i].l,sec[i].r)<<" ";
	//	cout<<f[sec[i].r]<<endl;
		add(1,1,rr,sec[i].r,sec[i].r,f[sec[i].r]);
	}
	cout<<f[sec[n].r];
	return 0;
}

posted @ 2021-10-21 23:10  Simex  阅读(28)  评论(0编辑  收藏  举报