codevs 1690 开关灯

来源:互联网 发布:阿里巴巴微商软件 编辑:程序博客网 时间:2024/05/17 01:56

线段树,贴代码

#include<iostream>#include<cstdio>using namespace std;struct xds{int l,r;bool add;int sum;}tree[400005];void build(int dq,int l,int r){tree[dq].l=l;tree[dq].r=r;if(l==r)return ;int mid=(l+r)>>1;build(dq<<1,l,mid);build(dq<<1|1,mid+1,r);}void spread(int dq){if(tree[dq].add){tree[dq<<1].add=!tree[dq<<1].add;tree[dq<<1|1].add=!tree[dq<<1|1].add;tree[dq<<1].sum=tree[dq<<1].r-tree[dq<<1].l+1-tree[dq<<1].sum;tree[dq<<1|1].sum=tree[dq<<1|1].r-tree[dq<<1|1].l+1-tree[dq<<1|1].sum;}tree[dq].add=0;}void up(int dq){tree[dq].sum=tree[dq<<1].sum+tree[dq<<1|1].sum;}void change(int l,int r,int dq){if(tree[dq].l>=l&&tree[dq].r<=r){tree[dq].add=!tree[dq].add;tree[dq].sum=tree[dq].r-tree[dq].l+1-tree[dq].sum;return ;}spread(dq);int mid=(tree[dq].l+tree[dq].r)>>1;if(mid>=l)change(l,r,dq<<1);if(mid<r)change(l,r,dq<<1|1);up(dq);}int ask(int l,int r,int dq){if(tree[dq].l>=l&&tree[dq].r<=r)return tree[dq].sum;spread(dq);int mid=(tree[dq].l+tree[dq].r)>>1;int ans=0;if(mid>=l)ans+=ask(l,r,dq<<1);if(mid<r)ans+=ask(l,r,dq<<1|1);return ans;}int main(){int n,m;scanf("%d%d",&n,&m);int c,x,y;build(1,1,n);for(int i=1;i<=m;i++){scanf("%d%d%d",&c,&x,&y);if(c==0)change(x,y,1);if(c==1)printf("%d\n",ask(x,y,1));}return 0;}

4 0
原创粉丝点击