2019-04-09 线段树

31 篇文章 0 订阅
21 篇文章 0 订阅

P3372 线段树1
线段树模板(LAZY):

#include <bits/stdc++.h>
const int maxn=100000+10;
using namespace std;
long long c[maxn*4],sum,lazy[maxn*4];
void init(int h,int s,int t){
    int mid=(s+t)/2;
    if(s==t)	
		scanf("%d",&c[h]);
    else{
        init(h*2,s,mid);
        init(h*2+1,mid+1,t);
        c[h]=c[h*2]+c[h*2+1];
    }
}
void pushdown(int h,int s,int t,int num){
    c[h]+=(t-s+1)*num;
    lazy[h]+=num;
}
void gx(int h,int s,int t,int L,int R,int num){
    int mid=(s+t)/2;
    if(L<=s&&t<=R){
        c[h]+=(t-s+1)*num;
        lazy[h]+=num;
    }
	else{
        if(lazy[h]){
            pushdown(h*2,s,mid,lazy[h]);
            pushdown(h*2+1,mid+1,t,lazy[h]);
            lazy[h]=0;
        }
        if(L<=mid)
			gx(h*2,s,mid,L,R,num);
        if(mid<R)
			gx(h*2+1,mid+1,t,L,R,num);
        c[h]=c[h*2]+c[h*2+1];
    }
}
void cx(int h,int s,int t,int L,int R){
    int mid=(s+t)/2;
    if(L<=s&&t<=R)		
		sum+=c[h];
    else{
        if(lazy[h]){
            pushdown(h*2,s,mid,lazy[h]);
            pushdown(h*2+1,mid+1,t,lazy[h]);
            lazy[h]=0;
        }
        if(L<=mid)
			cx(h*2,s,mid,L,R);
        if(mid<R)	
			cx(h*2+1,mid+1,t,L,R);	
    }
}
int main(){
    int i,j,k,m,n,x,y,z;
    cin>>n>>m;
    init(1,1,n);
    for(int i=1;i<=m;i++){
        scanf("%d",&k);
        if(k==1){
            scanf("%d%d%d",&x,&y,&z);
            gx(1,1,n,x,y,z);
        }
		else{
            scanf("%d%d",&x,&y);
            sum=0;                                                                                                  
            cx(1,1,n,x,y);
            printf("%lld\n",sum);
        }
    }
    return 0;
}

HDU1698

#include <bits/stdc++.h>
const int maxn=100000+10,maxm=100000+10;
using namespace std;
int a[maxn*2],c[maxm];
void init(int h,int s,int t){
	if(s==t)
		a[h]=0;
	else{
		init(h*2,s,(s+t)/2);
		init(h*2+1,(s+t)/2+1,t);
	}
}
void ts(int h,int s,int t,int L,int R,int ys){
	if(L<=s&&t<=R)
		a[h]=ys;
	else{
		if(a[h]>=0){
			a[h*2]=a[h*2+1]=a[h];
			a[h]=-1;
		}
		if(L<=(s+t)/2)
			ts(h*2,s,(s+t)/2,L,R,ys);
		if((s+t)/2+1<=R)
			ts(h*2+1,(s+t)/2+1,t,L,R,ys);
	}
}
void cal(int h,int s,int t){
	if(a[h]>=0)
		c[a[h]]+=t-s+1;
	else{
		cal(h*2,s,(s+t)/2);
		cal(h*2+1,(s+t)/2+1,t);
	}
}
int main(){
	int k,m,n,x,y;
	cin>>n>>m;
	init(1,1,n);
	for(int i=1;i<=m;i++){
		scanf("%d%d",&x,&y);
		ts(1,1,n,x,y,i);
	}
	cal(1,1,n);
	for(int i=0;i<=m;i++)
		if(c[i])
			printf("%d %d\n",i,c[i]);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值