B. Light bulbs (离散化+差分)
题目链接:https://nanti.jisuanke.com/t/41399
题意:n个灯刚开始是关的,m次操作对【L,R】内的全部的灯反转。问最后有几个灯亮着。
思路:刚开始差分直接便利了所有点,T了。所有只需要考虑哪些有贡献的2*m个点就行了,对于区间中哪些0的部分,就不需要遍历了。对于重复的点也不用管。
代码:
#include <bits/stdc++.h>
using namespace std;
struct node {
int id,x;
} a[3005];
int n,m,cnt;
bool rule( node a, node b )
{
return a.id<b.id;
}
int main()
{
int listt,l,r,i;
cin >> listt;
int ji = 1;
while ( listt-- ) {
cnt=0;
cin >> n >> m;
while ( m-- ) {
cin >> l >> r;
a[cnt].id=l; a[cnt++].x=1;
a[cnt].id=r+1; a[cnt++].x=-1;
}
sort( a,a+cnt,rule );
int sum = 0, ans=0;
for ( i=0; i<cnt-1; i++ ) {
sum += a[i].x;
if ( sum%2==1 ) {
ans += a[i+1].id-a[i].id;
}
}
cout << "Case #" << ji++ << ": " << ans << endl;
}
return 0;
}
/*
1 2 3 4 5 6 7 8 9 10
0 0 1 0 1 0 0 1 0 1
0 0 1 1 0 0 0 1 1 0
*/