开关灯(上海赛B题~迟到的题解)(超越算法的思维^_^)

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)FLIP(L,R) means to flip all bulbs xx 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 .

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, T . T 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 i , R_i
, indicating that the ii-th operation would like to flip all the bulbs from Li to Ri
, inclusive.(10001≤T≤1000) 0≤N≤106,(0≤M≤1000)

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.
题意就是一串灯泡,起始为关掉的,每次操作改变(l,r)之间变化原来状态,问m次操作后有多少开着的。

样例输入
2
10 2
2 6
4 8
6 3
1 1
2 3
3 4
样例输出
Case #1: 4
Case #2: 3

思路:对于每次操作进行排序,1,4(+1) 和3,5(+1)两次操作可以转成 1,3 和 5,6两次排序,选择两个数进行减操作,所有之和就是答案。

#include<iostream>
#include<algorithm>
#include<cstdio>
#define MAX 2001
using namespace std;
int p[MAX];
int main()
{
    int n,m,t;
    scanf("%d",&t);
    for(int icase=1;icase<=t;icase++){
        scanf("%d%d",&n,&m);
        int tot=0,now=0,sum=0,r,l,ans=0;
        for(int i=1;i<=m;i++){
            scanf("%d%d",&l,&r);
            p[++tot]=l;
            p[++tot]=r+1;
        }
        sort(p+1,p+tot+1);
        for(int i=1;i<=tot;i++){
            if(now!=p[i]){
                if(sum&1){
                    ans+=p[i]-now;
                }
                now=p[i];
            }
            sum++;
        }
        printf("Case #%d: %d\n",icase,ans);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值