There are N 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≤x≤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 LiLi and RiRi, indicating that the ii-th operation would like to flip all the bulbs from LiLi to RiRi , inclusive.
1≤T≤1000
1≤N≤10^6
1≤M≤1000
0≤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
-----------------------------------------------
O(MlogM),区间排序,左区间+1,右区间-1,求前缀和得出每一段的状态
------------------------------------------------
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2010;
pair<int, int> p[MAXN];
int main()
{
int T;
int iCase = 0;
int N, M;
scanf("%d", &T);
while (T--)
{
iCase++;
scanf("%d%d", &N, &M);
int tot = 0;
while(M--)
{
int l, r;
scanf("%d%d", &l, &r);
p[tot++] = make_pair(l, 1);//p[tot++].first=l,p[tot++].second=1;
p[tot++] = make_pair(r+1, -1);//##把范围储存到pair.first中了##//
//***左右范围用pair来储存的***/
}
sort(p, p+tot);//##把储存在first中的范围进行排序##/
int now = 0;
int ans = 0;
int sum = 0;
for (int i = 0; i < tot; i++)
{
if (now != p[i].first)//***用now来标记上一个边界的值***//
{
if (sum&1)
ans+=p[i].first - now;
now = p[i].first;
}
sum += p[i].second;
}//根据上面赋值的情况,有多少个1就有多少个-1,而只有sum==1的时候,p[i].first-p[i-1].first之间的灯是亮的
if (sum &1)//????
ans += N - now;//?????为什么会出现都做完了sum==1的情况???
printf("Case #%d: %d\n", iCase, ans);
}
return 0;
}