【hdu1198】Just a Hook 线段树区间赋值

       继续补线段树>_<。一句话题意:多组数据,区间赋值修改,最后求总和。线段树lazy tag直接上:

AC代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#define N 500005
using namespace std;

int n,m,c[N][2],sum[N],val[N];
int read(){
	int x=0; char ch=getchar();
	while (ch<'0' || ch>'9') ch=getchar();
	while (ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar(); }
	return x;
}
void pushdown(int k){
	if (val[k]!=-1){
		int l=c[k][0],r=c[k][1],mid=(l+r)>>1;
		val[k<<1]=val[k<<1|1]=val[k];
		sum[k<<1]=val[k]*(mid-l+1); sum[k<<1|1]=val[k]*(r-mid);
		val[k]=-1;
	}
}
void build(int k,int x,int y){
	c[k][0]=x; c[k][1]=y; val[k]=-1;
	if (x==y){ sum[k]=1; return; }
	int mid=(x+y)>>1; build(k<<1,x,mid); build(k<<1|1,mid+1,y);
	sum[k]=sum[k<<1]+sum[k<<1|1];
}
void mdy(int k,int x,int y,int v){
	int l=c[k][0],r=c[k][1],mid=(l+r)>>1;
	if (x==l && y==r){
		val[k]=v; sum[k]=v*(r-l+1); return;
	}
	pushdown(k);
	if (y<=mid) mdy(k<<1,x,y,v); else
	if (x>mid) mdy(k<<1|1,x,y,v); else{
		mdy(k<<1,x,mid,v); mdy(k<<1|1,mid+1,y,v);
	}
	sum[k]=sum[k<<1]+sum[k<<1|1];
}
int main(){
	int cas=read(),ri;
	for (ri=1; ri<=cas; ri++){
		n=read(); m=read(); build(1,1,n);
		while (m--){
			int x=read(),y=read(),z=read();
			mdy(1,x,y,z);
		}
		printf("Case %d: The total value of the hook is %d.\n",ri,sum[1]);
	}
	return 0;
}

by lych

2016.1.9

你可能感兴趣的:(线段树,tag,lazy)