Light bulbs (树状数组模板题)

Posted lengsong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Light bulbs (树状数组模板题)相关的知识,希望对你有一定的参考价值。

There are N light bulbs indexed from 00 to N1. Initially, all of them are off.

A FLIP operation switches the state of a contiguous subset of bulbs. FLIP(L, R)means to flip all bulbs x such that LxR. So for example, FLIP(3, 5) means to flip bulbs 3 , 4 and 5, and FLIP(5, 5)means to flip bulb 5.

Given the value of N and a sequence of M flips, count the number of light bulbs that will be on at the end state.

InputFile

The first line of the input gives the number of test cases, TT test cases follow. Each test case starts with a line containing two integers N and M, the number of light bulbs and the number of operations, respectively. Then, there are M more lines, the i-th of which contains the two integers Li? and Ri?, indicating that the ii-th operation would like to flip all the bulbs from Li? to Ri? , inclusive.

1T1000

1 N1000000

1 M1000

0Li?Ri?N1

OutputFile

For each test case, output one line containing Case #x: y, where xx is the test case number (starting from 11) and yyis the number of light bulbs that will be on at the end state, as described above.

样例输入

2
10 2
2 6
4 8
6 3
1 1
2 3
3 4

样例输出

Case #1: 4
Case #2: 3
#include <bits/stdc++.h>
#pragma GCC optimize(3)
using namespace std;
const int maxn=2e3+5;
int str[maxn],str2[maxn],c[1000005],n,m;
int ask(int x)

    int ans=0;
    for(; x; x-=x&-x)ans+=c[x];
    return ans;

void add(int x,int y)

    for(; x<=n; x+=x&-x)c[x]+=y;

template<class T>
inline void read(T&x)

    T ans=0,f=1;
    char ch=getchar();
    while(ch<‘0‘||ch>‘9‘)
    
        if(ch==‘-‘)f=-1;
        ch=getchar();
    
    while(ch>=‘0‘&&ch<=‘9‘)
    
        ans=ans*10+ch-‘0‘;
        ch=getchar();
    
    x=ans*f;

int main()

    int t,l,r,cnt=0,k=0;
    read(t);
    while(t--)
    
        cnt=0;
        read(n);
        read(m);
        int m2=m;
        while(m2--)
        
            read(l);read(r);
            ++l,++r;
            add(l,1);
            add(r+1,-1);
            str[++cnt]=l,str2[cnt]=l;
            str[++cnt]=r+1,str2[cnt]=r+1;
        
        sort(str+1,str+cnt+1);
        int cnt2=0;
        for(int i=1; i<=cnt; ++i)
        
            if(str[i]!=str[cnt2])
                str[++cnt2]=str[i];
        
        int ans=0,flag;
        for(int i=1; i<cnt2; ++i)
        
            flag=ask(str[i]);
            if((flag&1)==1)
                ans+=str[i+1]-1-str[i]+1;
        
        printf("Case #%d: %d\n",++k,ans);
        for(int i=1; i<=2*m; i+=2)
        
            add(str2[i],-1);
            add(str2[i+1],1);
        
    
    return 0;

  

以上是关于Light bulbs (树状数组模板题)的主要内容,如果未能解决你的问题,请参考以下文章

几道树状数组的模板题

树状数组模板题(特强浓雾

hiho 172周 - 二维树状数组模板题

BZOJ 1901Zju 2112 Dynamic Rankings 动态K值 树状数组套主席树模板题

树状数组模板题 P1904

P3374 模板树状数组 1(单点修改区间查询)(树状数组)