light bulbs(2019上海网络赛ICPC)

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值