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 xsuch 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 Rii, indicating that the i-th operation would like to flip all the bulbs from Li to Ri, inclusive.
1≤T≤1000
1≤N≤1e6
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
题意:T组样例,给定N个灯泡,M个操作,[L,R]代表打开区间内灯泡,若灯泡为开状态就关闭。
线段树超内存,这几天没课了总结下这个内存这个问题,真的坑人
思路: 若M=2,操作区间分别是[1, 2] [3, 4] ans = (2+1)-1 + (4+1)-3 = 4
若M=2,操作区间分别是[1, 4] [2, 3] ans = 2-1 + (4+1)-(3+1) = 4 观察得,将右端点+1,操作的区间的左右端点排序得到的序列,只需要遍历一次m个操作,求前缀和
一个区间若被操作偶数次相当于没有操作,只有操作奇数次的区间的灯的状态才改变,可以通过M次操作的左右端点判断有哪些区间被操作了奇数次。
//c++11 AC c++14超时
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1e5+10;
int a[maxn];
int main() {
int T;
cin >> T;
for(int k=1;k<=T;k++) {
int n,m;
int ans = 0;
cin >> n >> m;
for(int i=0;i<2*m;i++) {
if(i%2==0)
cin >> a[i];
else {
cin >> a[i];
a[i]++;
}
}
sort(a,a+2*m);
for(int i=0;i<2*m;i+=2) {
ans = ans+(a[i+1]-a[i]);
}
cout << "Case #" << k << ": " << ans << endl;
}
return 0;
}