【codevs1690】开关灯,线段树练习

开关灯 USACO
时间限制: 1 s
空间限制: 128000 KB
题目等级 : 钻石 Diamond
题解
题目描述 Description
YYX家门前的街上有N(2<=N<=100000)盏路灯,在晚上六点之前,这些路灯全是关着的,六点之后,会有M(2<=m<=100000)个人陆续按下开关,这些开关可以改变从第i盏灯到第j盏灯的状态,现在YYX想知道,从第x盏灯到第y盏灯中有多少是亮着的(1<=i,j,x,y<=N)

输入描述 Input Description
第 1 行: 用空格隔开的两个整数N和M
第 2..M+1 行: 每行表示一个操作, 有三个用空格分开的整数: 指令号(0代表按下开关,1代表询问状态), x 和 y
输出描述 Output Description
第 1..询问总次数 行:对于每一次询问,输出询问的结果

样例输入 Sample Input
4 5
0 1 2
0 2 4
1 2 3
0 2 4
1 1 4

样例输出 Sample Output
1
2
写在前面:Fighting!
——————————————————————————————————————————————
思路:延迟标记加好,别无。
代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
using namespace std;
struct os
{
    int yes,total;
    bool flag;
}tree[400010];
int n,m;
int k,head,tail;
void f(int root)
{
    tree[root].yes=tree[root].total-tree[root].yes;
}
void build(int root,int begin,int end)
{
    if (begin>end) return;
    tree[root].total=end-begin+1;
    if (begin==end) return;
    int mid=(begin+end)/2;
    build(root*2,begin,mid);
    build(root*2+1,mid+1,end);
}
void pushdown(int root)
{
    if (!tree[root].flag) return;
    tree[root*2].flag=!tree[root*2].flag;
    tree[root*2+1].flag=!tree[root*2+1].flag;
    f(root*2);
    f(root*2+1);
    tree[root].flag=0;
}
void update(int root,int begin,int end)
{
    if (begin>=head&&end<=tail) {f(root);tree[root].flag=!tree[root].flag;return;}
    pushdown(root);
    int mid=(begin+end)/2;
    if (head<=mid) update(root*2,begin,mid);
    if (tail>mid)  update(root*2+1,mid+1,end);
    tree[root].yes=tree[root*2].yes+tree[root*2+1].yes;
}
int get(int root,int begin,int end)
{
    if (begin>=head&&end<=tail) return tree[root].yes;
    pushdown(root);
    int mid=(begin+end)/2,ans=0;
    if (head<=mid) ans+=get(root*2,begin,mid);
    if (tail>mid)  ans+=get(root*2+1,mid+1,end);
    return ans;
}
main()
{
    scanf("%d%d",&n,&m);
    build(1,1,n);
    for (int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&k,&head,&tail);
        if (k==0) update(1,1,n);
        else printf("%d\n",get(1,1,n));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台智能台

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值