时间限制:1000ms 内存:8192K
There are N light bulbs indexed from 0 to N−1. 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 L≤x≤R. 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, T. T 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 i-th operation would like to flip all the bulbs from Li to Ri , inclusive.
1≤T≤1000
1≤N≤106
1≤M≤1000
0≤Li≤Ri≤N−1
OutputFile
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is 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
题目大意:
n个灯,初始全为不亮,共m个操作,每次操作包含两个数l和r,表示改变该区间内所有灯的状态(亮->不亮,不亮->亮)
思路:
这题如果线段树去写的话会爆内存,差不多只能开两倍的内存
用到差分的思想(左端点位置的值+1,右端点+1位置的值-1),考虑到m比较小,n比较大,差分后直接求前缀和的话还是会超时,所以需要考虑对m进行操作
对每个修改的点按位置进行排序,用sum求和,当sum为奇数时,说明与前一个位置相差奇数次操作,相差的区间内灯全亮
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 6 const int N=1e6+5,M=2005; 7 int a[N]; 8 9 struct Node{ 10 int index,num; 11 }node[M]; 12 13 bool cmp(Node x,Node y){ 14 return x.index<y.index; 15 } 16 17 int main(){ 18 int t,n,m,l,r,ca=0; 19 scanf("%d",&t); 20 while(t--){ 21 int k=0; 22 memset(a,0,sizeof a); 23 scanf("%d%d",&n,&m); 24 while(m--){ 25 scanf("%d%d",&l,&r); 26 node[k].index=l,node[k++].num=1; 27 node[k].index=r+1,node[k++].num=-1; 28 } 29 sort(node,node+k,cmp); 30 int sum=0,res=0; 31 for(int i=1;i<k;i++){ 32 sum+=node[i].num; 33 if(sum&1){ 34 res+=node[i].index-node[i-1].index; 35 } 36 } 37 printf("Case #%d: %d ",++ca,res); 38 } 39 }