2019上海网络赛B. Light bulbs(差分)

题干:

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≤ 1 0 6 10^6 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

思路:

本题是一个区间修改问题,状态只有0和1,比较容易想到的是后缀和用数组res[i]表示从i到n的所有灯泡变换的次数,使用now表示以变化的次数,每次now+res[i],now%2则表示当前灯泡的状态。

其实这个题可以转换为每次操作对[L,R]的所有数进行+1操作,求最后有多少个奇数。(这就是经典的差分问题了)

y因为本题N的范围是[1, 1 0 6 10^6 106],o(N)的复杂度加上多组输入还是会超时,所以考虑用差分。
然后我们考虑从范围是[1,1000]的M入手,首先存储所有操作->(l,1)(r+1,-1)(r+1是因为右边界本身被触发了一次开关)并按first排序。
用now表示当前的位置,sum表示从now到当前灯泡的开关状态。
例如:6 3
1 1
2 3
3 4
这组数据得到的pair数组为(1,1)(2,-1)(2,1)(3,1)(4.-1)(5,-1)
now=1 2 2 3 4 5
sum=1 0 1 2 1 0
ans= 0 1 1 2 2 3

#include
#include
#include
#include
#include
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++){
			if(now!=p[i].first){
				if(sum&1){
					ans+=p[i].first-now;
				}
				now=p[i].first;
			}
			sum+=p[i].second;
		}
		printf("Case #%d: %d\n",k,ans);
	}
	return 0;
}

//TLE的代码还是放上来了
#include
#include
#include
#include
#include
using namespace std;
int res[1000010];
int main()
{
	int t,t1,x,y,n;
	scanf("%d",&t1);
	for(int k=1;k<=t1;k++){
		scanf("%d%d",&n,&t); 
		for(int i=0;i<=n;i++)
			res[i]=0;
		while(t--){
			scanf("%d%d",&x,&y);
			res[x]++;
			res[y+1]++;
		}
		int now=0,ans=0;
		for(int i=0;i<n;i++){
			now+=res[i];
			if(now%2==1)
				ans++;
		}
		printf("Case #%d: %d\n",k,ans);
	}
	return 0;
}

你可能感兴趣的:(差分,模板题)