ACwing 422校门外的树

题目描述:

某校大门外长度为L的马路上有一排树,每两棵相邻的树之间的间隔都是1米。

我们可以把马路看成一个数轴,马路的一端在数轴0的位置,另一端在L的位置;数轴上的每个整数点,即0,1,2,……,L,都种有一棵树。

由于马路上有一些区域要用来建地铁。

这些区域用它们在数轴上的起始点和终止点表示。

已知任一区域的起始点和终止点的坐标都是整数,区域之间可能有重合的部分。

现在要把这些区域中的树(包括区域端点处的两棵树)移走。

你的任务是计算将这些树都移走后,马路上还有多少棵树。

输入格式

输入文件的第一行有两个整数L和M,L代表马路的长度,M代表区域的数目,L和M之间用一个空格隔开。

接下来的M行每行包含两个不同的整数,用一个空格隔开,表示一个区域的起始点和终止点的坐标。

输出格式

输出文件包括一行,这一行只包含一个整数,表示马路上剩余的树的数目。

数据范围

1≤L≤100001≤L≤10000,
1≤M≤1001≤M≤100

输入样例:

500 3
150 300
100 200
470 471

输出样例:

298

暴力做法:

#include <iostream>
#include <cstdio>

using namespace std;
const int MAX = 109;

int n, m, s, e;
bool vis[10009];


int main()
{
    scanf("%d%d", &n, &m);
    int sum = n + 1;
    for(int i = 0; i < m; i++)
    {
        scanf("%d%d", &s, &e);
        for(int j = s; j <= e; j++)
        {
            if(!vis[j])
            {
                vis[j] = true;
                sum --;
            }
        }

    }

    printf("%d\n", sum);
    return 0;
}

区间合并做法:

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;
const int MAX = 109;

int n, m, s, e;
struct Tree
{
    int l, r;
}a[MAX];

bool cmp(Tree x, Tree y)
{
    return x.l < y.l;
}

int main()
{
    scanf("%d%d", &n, &m);
    int sum = n + 1;

    for(int i = 0; i < m; i++)
    {
        scanf("%d%d", &a[i].l, &a[i].r);
    }

    sort(a, a + m, cmp);

    int L, R;
    L = a[0].l;
    R = a[0].r;

    for(int i = 1; i < m; i++)
    {
        if(a[i].l <= R)
            R = max(R, a[i].r);
        else
        {
            sum -= (R - L + 1);
            L = a[i].l;
            R = a[i].r;
        }
    }
    sum -= (R - L + 1);

    printf("%d\n", sum);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44620183/article/details/113120785