Light bulbs 上海网络赛

There are NN 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 \leq x \leq 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 L_iLi​ and R_iRi​, indicating that the ii-th operation would like to flip all the bulbs from L_iLi​ to R_iRi​ , inclusive.

1 \leq T \leq 10001≤T≤1000

1 \leq N \leq 10^61≤N≤106

1 \leq M \leq 10001≤M≤1000

0 \leq L_i \leq R_i \leq N-10≤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

大体意思:n个灯泡,索引从 0 到 n-1,一开始所有的灯泡都是关闭的,

给出m次操作,每次操作都使该范围内的灯泡的状态反转,打开的关上,

关上的打开。

输出最后状态为开的灯泡

暴力显然不可以

看了题解明白了

说的是离散化+差分;虽然俺也不知道是啥,但是代码看懂了

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=2000+10;
pair<int,int> mp[maxn];
int t,n,m,x,y;
int main()
{
	scanf("%d",&t);
	int cnt=0;
	while(t--)	
	{
		int tot=0;
		cnt++;
		scanf("%d %d",&n,&m);
		while(m--)
		{
			scanf("%d %d",&x,&y);
			mp[tot++]=make_pair(x,1);
			mp[tot++]=make_pair(y+1,-1);
		}
		sort(mp,mp+tot);
		int ans=0;
		int sum=0;
		int now=0;
		for(int i=0;i<tot;i++)
		{
			if(now!=mp[i].first)
			{
				if(sum&1)
				{
					ans+=mp[i].first-now;		
				}
				now=mp[i].first;	
			}
			sum+=mp[i].second;
		}
		if(sum&1) ans+=n-now;
		printf("Case #%d: %d\n",cnt,ans);
	}
	return 0;
} 
发布了51 篇原创文章 · 获赞 21 · 访问量 3097

猜你喜欢

转载自blog.csdn.net/qq_44115065/article/details/100922341