• 题解 P3870 【[TJOI2009]开关】


    又是一道线段树。。。

    本题其实是一道裸题。。。不明白为什么是这个难度标签。

    思路很明显,用tree[i].val表示区间内开着的灯的数量。

    然后常规操作(建树、查询、修改)就可以了。

    最后:lazy tag是个好东西。

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <algorithm>
     4 #define lson pos << 1
     5 #define rson pos << 1 | 1
     6 using namespace std;
     7 
     8 const int maxn = 100100;
     9 
    10 int n, m, c, a, b;
    11 
    12 struct node {
    13     int l,r;
    14     int val;          
    15     int lazy;
    16 } tree[maxn << 2];
    17 
    18 inline void Pushup(int pos) {
    19     tree[pos].val = tree[lson].val + tree[rson].val;
    20 }
    21 
    22 void Pushdown(int pos) {
    23     if(tree[pos].lazy) {
    24         tree[lson].lazy ^= 1; 
    25         tree[rson].lazy ^= 1;
    26         tree[lson].val = tree[lson].len() - tree[lson].val;
    27         tree[rson].val = tree[rson].len() - tree[rson].val;
    28         tree[pos].lazy = 0;
    29     }
    30 }
    31 
    32 void Build(int l, int r, int pos) {  
    33     tree[pos].l = l;
    34     tree[pos].r = r;
    35     tree[pos].val = 0;
    36     if(l == r) return ;
    37     int mid = (l + r) >> 1;
    38     Build(l, mid, lson);
    39     Build(mid + 1, r, rson);
    40 }
    41 
    42 void Update(int l, int r, int pos) {
    43     if(l <= tree[pos].l && tree[pos].r <= r) {
    44         tree[pos].val = tree[pos].len() - tree[pos].val;
    45         tree[pos].lazy ^= 1;
    46         return ;
    47     }
    48     Pushdown(pos);
    49     int mid = tree[pos].mid();
    50     if(l <= mid) Update(l, r, lson);
    51     if(r > mid) Update(l, r, rson);
    52     Pushup(pos);
    53 }
    54 
    55 int Query(int l, int r, int pos) {
    56     if(l <= tree[pos].l && tree[pos].r <= r) {
    57         return tree[pos].val;
    58     }
    59     Pushdown(pos);
    60     int mid = tree[pos].mid();
    61     int ans = 0;
    62     if(l <= mid)  ans += Query(l, r, lson);
    63     if(r > mid)   ans += Query(l, r, rson);
    64     return ans;
    65 }
    66 
    67 int main() {
    68     cin >> n >> m;
    69     Build(1, n, 1);
    70     while(m--) {
    71         cin >> c >> a >> b;
    72         if(c == 0) {
    73             Update(a, b, 1);
    74         } else {
    75             cout << Query(a, b, 1) << endl;
    76         }
    77     }
    78 }

    话说回来。。。这道题好像在洛谷上有不知一道重题,可以n倍经验了!!

  • 相关阅读:
    ASP.NET的最新安全漏洞Important: ASP.NET Security Vulnerability
    Sql常用日期格式
    倒计时 服务器时间 .NET js javascript
    “备份集中的数据库备份与现有的数据库不同”解决方法
    2010年最佳jQuery插件
    jQuery1.4与json格式兼容问题
    .NET结束外部进程 C#结束外部进程
    十步优化SQL Server中的数据访问
    SQL游标的使用与语法
    SQL2005、SQL2008如何压缩日志文件(log) 如何清除日志
  • 原文地址:https://www.cnblogs.com/ilverene/p/9819026.html
Copyright © 2020-2023  润新知