SDNUOJ 1092

Description
某校大门外长度为L的马路上有一排树,每两棵相邻的树之间的间隔都是1米。我们可以把马路看成一个数轴,马路的一端在数轴0的位置,另一端在L的位置;数轴上的每个整数点,即0,1,2,……,L,都种有一棵树。
由于马路上有一些区域要用来建地铁。这些区域用它们在数轴上的起始点和终止点表示。
已知任一区域的起始点和终止点的坐标都是整数,区域之间可能有重合的部分。现在要把这些区域中的树(包括区域端点处的两棵树)移走。你的任务是计算将这些树都移走后,马路上还有多少棵树。
Input
输入的第一行有两个整数:L(1 <= L <= 10000)和 M(1 <= M <= 100),L代表马路的长度,M代表区域的数目,L和M之间用一个空格隔开。接下来的M行每行包含两个不同的整数(小于2147483648),用一个空格隔开,表示一个区域的起始点和终止点的坐标。
Output
输出包括一行,这一行只包含一个整数,表示马路上剩余的树的数目。
Sample Input
500 3
150 300
100 200
470 471
Sample Output
298

看群里聊天记录看到在讨论这题,本来不会做,听他们一说就按照他们的做法去做了,也是一种思想…

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;

bool area[10005];

int main()
{
    int l, n;
    int a[1005];
    int b[1005];
    cin >> l >> n;
    int max_b = 0;
    int min_a = 1000000;
    for(int i = 0; i < n; ++i)
    {
        scanf("%d%d", &a[i], &b[i]);
        if(min_a > a[i])
            min_a = a[i];
        if(max_b < b[i])
            max_b = b[i];
    }
    for(int i = 0; i < n; ++i)
    {
        for(int j = a[i]; j <= b[i]; ++j)
        {
            area[j] = 1;
        }
    }
//    cout << min_a << " " << max_b << '\n';
    bool word = 0;
    int sum = 0;
    int start;
    int over;
    for(int i = min_a; i < max_b + 5; ++i)
    {
        if(word == 0 && area[i] == 1)
        {
            start = i;
//            cout << start << '\n';
            word = 1;
            continue;
        }
        if(area[i] == 0 && word == 1)
        {
            over = i - 1;
//            cout << over << '\n';
            sum += over - start + 1;
            word = 0;
            continue;
        }
    }
    cout << l - sum + 1 << '\n';
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhaobaole2018/article/details/84916425