【USACO 2008 Nov Gold】 3.Light Switching(lites 开关灯) 区间修改线段树

题意:

n、m,n个灯,m次操作

两种操作 0: 这段区间全部状态取反,初始全部为0

         1: 询问这段区间有几个灯是亮的。


裸线段树,弱爆了。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define N 101000
#define inf 0x3f3f3f3f
using namespace std;

struct Segment_Tree
{
	int l,r,x;
	bool flag;
}s[N<<2];
int n,m;
void pushup(int x){s[x].x=s[x<<1].x+s[x<<1|1].x;}
void pushdown(int x)
{
	if(s[x].flag)
	{
		s[x].flag=0;
		if(s[x].l<s[x].r)
		{
			s[x<<1].flag^=1;
			s[x<<1|1].flag^=1;
		}
		s[x].x=s[x].r-s[x].l+1-s[x].x;
	}
}
void build(int note,int l,int r)
{
	s[note].l=l;
	s[note].r=r;
	if(l==r)return ;
	int mid=l+r>>1;
	build(note<<1,l,mid);
	build(note<<1|1,mid+1,r);
}
void add(int note,int l,int r)
{
	if(s[note].l==l&&s[note].r==r)
	{
		s[note].flag^=1;
		pushdown(note);
		return ;
	}
	pushdown(note);
	int mid=s[note].l+s[note].r>>1;
	if(r<=mid)add(note<<1,l,r),pushdown(note<<1|1);
	else if(l>mid)add(note<<1|1,l,r),pushdown(note<<1);
	else add(note<<1,l,mid),add(note<<1|1,mid+1,r);
	pushup(note);
}
int query(int note,int l,int r)
{
	pushdown(note);
	if(s[note].l==l&&r==s[note].r)return s[note].x;
	int mid=s[note].l+s[note].r>>1;
	if(r<=mid)return query(note<<1,l,r);
	else if(l>mid)return query(note<<1|1,l,r);
	else return query(note<<1,l,mid)+query(note<<1|1,mid+1,r);
}
int main()
{
	int i,j,k;
	int a,b,c;
	scanf("%d%d",&n,&m);
	build(1,1,n);
	while(m--)
	{
		scanf("%d%d%d",&a,&b,&c);
		if(a==0)add(1,b,c);
		else printf("%d\n",query(1,b,c));
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值