时间限制:1000ms 内存:8192K
There are NN light bulbs indexed from 00 to N-1N−1. Initially, all of them are off.
A FLIP operation switches the state of a contiguous subset of bulbs. FLIP(L, R)FLIP(L,R) means to flip all bulbs xx such that L \leq x \leq RL≤x≤R. So for example, FLIP(3, 5)FLIP(3,5) means to flip bulbs 33 , 44 and 55, and FLIP(5, 5)FLIP(5,5) means to flip bulb 55.
Given the value of NN and a sequence of MM 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. TT test cases follow. Each test case starts with a line containing two integers NN and MM, the number of light bulbs and the number of operations, respectively. Then, there are MM more lines, the ii-th of which contains the two integers L_iLi and R_iRi, indicating that the ii-th operation would like to flip all the bulbs from L_iLi to R_iRi , inclusive.
1 \leq T \leq 10001≤T≤1000
1 \leq N \leq 10^61≤N≤106
1 \leq M \leq 10001≤M≤1000
0 \leq L_i \leq R_i \leq N-10≤Li≤Ri≤N−1
OutputFile
For each test case, output one line containing Case #x: y, where xx is the test case number (starting from 11) and yy 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\n",++ca,res); 38 } 39 }