POJ1201-Intervals-线段树+贪心

原题链接
题意:给定一些区间,每个区间里必须取ci个数,这些数组成一个集合z,求z的最少的元素数
思路:由于如果两个区间如果有重复取的元素,那么这个元素一定是在左边的这个区间的最右边的那些元素。所以我们按照区间的右边界排序后,总是如果当前区间还需要取数,那么就从右往左取还没有被取的数即可。然后就可以用线段树来维护一段区间内已经被取走的数的总数。这样问题的复杂度就降到了O(NlogN)的程度了

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 50000 + 10;
typedef struct line
{
	int l,r,c;
}line;
line a[maxn];
bool cmp(line x,line y){
	if(x.r<y.r) return true;
	else if(x.r>y.r) return false;
	else{
		if(x.l<y.l) return true;
		else return false;
	}
}
typedef struct addtree
{
	//区间用[ql,qr],[l,r]表示
	int t[maxn * 4];
	//向上更新区间和函数
	//比如区间[1,8]我们要在5位置将原来的数加上2就需要传入(5,2,1,1,8)
	void update(int loc,int x,int k,int l,int r){
		if(l==r) t[k]+=x;
		else{
			int mid = l + (r-l)/2;
			if(loc<=mid) update(loc,x,k*2,l,mid);
			else update(loc,x,k*2+1,mid+1,r);
			t[k] = t[k*2] + t[k*2+1];
		}
	}
	//查询区间和
	//比如区间[1,8]我们要查询[3,6]区间的区间和就要传入(3,6,1,1,8)
	int query(int ql,int qr,int k,int l,int r){
		if(ql<=l && r<=qr) return t[k];
		int mid = l + (r-l)/2,ans=0;
		if(ql<=mid) ans+=query(ql,qr,k*2,l,mid);
		if(mid+1<=qr) ans+=query(ql,qr,k*2+1,mid+1,r);
		return ans;
	}
}addtree;//单点加上一个值求区间和的线段树
addtree at;
bool used[maxn];
int main(){
	int n,res=0;
	cin >> n;
	for(int i=0;i<n;i++) scanf("%d%d%d",&a[i].l,&a[i].r,&a[i].c);
	sort(a,a+n,cmp);
	memset(at.t,0,sizeof(at.t));
	memset(used,false,sizeof(used));
	for(int i=0;i<n;i++){
		int left = a[i].c - at.query(a[i].l,a[i].r,1,0,maxn);
		if(left>0){
			res+=left;
			int begin=a[i].r;
			while(left>0){//如果使用过就要向后顺延
				while(used[begin]) begin--;
				used[begin]=true;
				at.update(begin,1,1,0,maxn);
				left--;
			}
		}
	}
	cout << res << endl;
	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

门豪杰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值