Light bulbs(2019年亚洲区域(上海)网络赛B )

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_iL
i

and R_iR
i

, indicating that the ii-th operation would like to flip all the bulbs from L_iL
i

to R_iR
i

, inclusive.

1 \leq T \leq 10001≤T≤1000

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

1 \leq M \leq 10001≤M≤1000

0 \leq L_i \leq R_i \leq N-10≤L
i

≤R
i

≤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没有考虑M就超时,答案的正解是从M考虑,将区间端点排序,左端点+1,右端点-1。解法跟扫描线差不多。

#include <bits/stdc++.h>
using namespace std;

const int MAXN = 2010;
pair<int, int> p[MAXN];
int main() {
  int T;
  int iCase = 0;
  int N, M;
  scanf("%d", &T);
  while (T--) {
    iCase++;
    scanf("%d%d", &N, &M);
    int tot = 0;
    while(M--) {
      int l, r;
      scanf("%d%d", &l, &r);
      p[tot++] = make_pair(l, 1);
      p[tot++] = make_pair(r+1, -1);
    }
    sort(p, p+tot);
    int now = 0;
    int ans = 0;
    int sum = 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;
    }
    if (sum &1) ans += N - now;
    printf("Case #%d: %d\n", iCase, ans);
  }
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

轩辕青山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值