The tree outside ACwing 422 school gate

Title description:

There is a row of trees on the road with length L outside the gate of a school, and the distance between every two adjacent trees is 1 meter.

We can think of a road as a number line, one end of the road is at the position of 0 on the number line, and the other end is at the position of L; each integer point on the number line, namely 0, 1, 2, ..., L, has a tree planted .

Because there are some areas on the road to be used to build subways.

These areas are represented by their starting and ending points on the number line.

It is known that the coordinates of the start point and the end point of any area are integers, and there may be overlapping parts between the areas.

Now we need to remove the trees in these areas (including the two trees at the end of the area).

Your task is to calculate how many trees are left on the road after all these trees are removed.

Input format

The first line of the input file has two integers L and M. L represents the length of the road, M represents the number of areas, and L and M are separated by a space.

Each of the next M lines contains two different integers, separated by a space, indicating the coordinates of the start and end points of an area.

Output format

The output file includes one line, this line contains only an integer, indicating the number of trees remaining on the road.

data range

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

Input sample:

500 3
150 300
100 200
470 471

Sample output:

298

Violent practices:

#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;
}

Interval merging practices:

#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;
}

 

 

Guess you like

Origin blog.csdn.net/weixin_44620183/article/details/113120785