题目:
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≤10610^610
6
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
代码:
#include<bits/stdc++.h>
using namespace std;
pair<int,int>p[2020];
int main()
{
int t1,t,n,m,l,r;
scanf("%d",&t1);
for(int k=1;k<=t1;k++){
int tot=0;
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++){
scanf("%d%d",&l,&r);
p[tot++]=make_pair(l,1);
p[tot++]=make_pair(r+1,-1);
}
sort(p,p+tot);
int sum=0,now=0,ans=0;
for(int i=0;i<tot;i++){
/// cout<<"first second: "<<p[i].first<<" "<<p[i].second<<endl;
if(now!=p[i].first){
if(sum&1){
ans+=p[i].first-now;
/// cout<<"p[i].first-now: "<<p[i].first-now<<endl;
}
now=p[i].first;
}
sum+=p[i].second;
/// cout<<"now ans sum :"<<now<<" "<<ans<<" "<<sum<<endl<<endl;
}
///if(sum&1) ans+=n-now; 最后sum为0,此句可写可不写
printf("Case #%d: %d\n",k,ans);
}
return 0;
}
第一次写这个心好累…代码都弄不进来一句一句复制??
线段俩端是输入,ans是所加的长度,自己做的时候也有这样排序考虑但是没考虑好没有用到+1-1,用了其他判断来次数…结果wa,弄了个图片更容易理解
别人说是差分的签到题…
庆祝一下我第一次写博客!!!!