【题解】洛谷 P1083 借教室

[TOC]

###题目
P1083 借教室
###思路
线段树。需要的操作为区间修改,区间查询。维护每个区间的最小值就好。
###\(Code\)

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<algorithm>
#define lson now<<1
#define rson now<<1|1
#define MAXN 1000001
#define rr register
#define min_(a,b) a>b?b:a
using namespace std;
int n,m;
struct Node{
	int l,r,minn;
	int lazy;
}tree[MAXN<<2];

inline void read(int &T) {
	int x=0;bool f=0;char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')f=!f;c=getchar();}
	while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
	T=f?-x:x;
}

inline void write(int x) {
	if(x<0) putchar('-'),write(-x);
	else {
		if(x/10) write(x/10);
		putchar(x%10+'0');
	}
}

void build(int l,int r,int now) {
	tree[now].l=l,tree[now].r=r;
	if(tree[now].l==tree[now].r) {
		read(tree[now].minn);
		return;
	}
	int mid=(tree[now].l+tree[now].r)>>1;
	build(l,mid,lson),build(mid+1,r,rson);
	tree[now].minn=min_(tree[lson].minn,tree[rson].minn);
}

inline void pushdown(int now) {
	if(tree[now].l==tree[now].r) return;
	tree[lson].lazy+=tree[now].lazy;
	tree[rson].lazy+=tree[now].lazy;
	tree[lson].minn-=tree[now].lazy;
	tree[rson].minn-=tree[now].lazy;
	tree[now].lazy=0;
}

int query(int x,int y,int now) {
	if(tree[now].l>=x&&tree[now].r<=y) {
		return tree[now].minn;
	}
	if(tree[now].lazy) pushdown(now);
	int mid=(tree[now].l+tree[now].r)>>1,minnn=0x7fffffff;
	if(x<=mid) minnn=min(minnn,query(x,y,lson));
	if(y>mid) minnn=min(minnn,query(x,y,rson));
	return minnn;
}

void update(int x,int y,int k,int now) {
	if(tree[now].l>=x&&tree[now].r<=y) {
		tree[now].minn-=k;
		tree[now].lazy+=k;
		return;
	}
	if(tree[now].lazy) pushdown(now);
	int mid=(tree[now].l+tree[now].r)>>1;
	if(x<=mid) update(x,y,k,lson);
	if(y>mid) update(x,y,k,rson);
	tree[now].minn=min_(tree[lson].minn,tree[rson].minn);
}

int main() {
	read(n),read(m);
	build(1,n,1);
	for(rr int i=1,x,y,k;i<=m;++i) {
		read(k),read(x),read(y);
		if(query(x,y,1)<k) {
			puts("-1");
			write(i);
			return 0;
		}else update(x,y,k,1);
	}
	puts("0");
	return 0;
}
posted @ 2019-10-06 16:25  yu__xuan  阅读(236)  评论(0编辑  收藏  举报