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 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 Li and Ri , indicating that the ii-th operation would like to flip all the bulbs from Li and Ri , inclusive.
1≤T≤1000
1≤N≤106
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盏灯,现在对这n盏灯进行m次操作,每次操作给你一个区间,对这个区间的灯进行这样的操作,如果这盏灯是开着的就将其关掉,如果是关着的就将其打开,最后问m次操作之后开着的灯的数量。
解题思路:这道题如果用普通的暴力,这样会超时,因此只能另寻它路,仔细想过之后你会发现最后求的灯亮的个数只与左端点有关,具体见一下代码,自己模拟一遍就懂了。
程序代码:
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int main()
{
int i,j,a[2000],n,m,t,x,y,sum,T,r1=0;
scanf("%d",&T);
while(T--)
{
r1++;
scanf("%d%d",&n,&m);
t=sum=0;
memset(a,0,sizeof(a));
for(i=1;i<=m;i++)
{
scanf("%d%d",&x,&y);
a[t++]=x;
a[t++]=y+1;
}
sort(a,a+2*m);
for(i=0;i<t;i+=2)
sum+=a[i+1]-a[i];
printf("Case #%d: %d\n",r1,sum);
}
return 0;
}