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 LxR*. 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 M*, the number of light bulbs and the number of operations, respectively. Then, there are M more lines, the i*-th of which contains the two integers Li and Ri, indicating that the i-th operation would like to flip all the bulbs from Li to Ri , inclusive.

1≤T≤1000

1≤N≤106

1≤M≤1000

0≤LiRiN−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个区间(l,r),这个区间内的每个灯会发生变化,关—>开,开—>关。

问你最后有多少亮着的灯。最初灯都是关着的。

链接:

https://nanti.jisuanke.com/t/41399

思路:

差分。

我们可以利用差分来处理区间。(l)+1,(r+1)+1。

我们可以对端点进行排序,直接跑一遍2*m即可。

如果是左端点则+1,右端点-1.

区间是左闭右开只有是奇数的时候是亮的。所以R-L即可。

代码:

#include 
using namespace std;
const int maxn = 2000+50;
pair<int ,int> p[maxn];
int main()
{
    ios::sync_with_stdio(false);
    int t, n, m, l, r;
    scanf("%d", &t);
    for(int Case = 1; Case <= t; Case++) {
        scanf("%d%d", &n, &m);
        int tot = 0;
        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 ans = 0;
        int sum = 0;
        for(int i = 0; i < tot; i++) {
            if(sum & 1) {
                ans += p[i].first - p[i-1].first;
            }
            sum += p[i].second;
        }
        printf("Case #%d: %d\n", Case, ans);
    }


    return 0;
}

你可能感兴趣的:(技巧,差分,网络赛)