AcWing every day during winter vacation 2021-01-16 The tree outside the school gate

AcWing 422.
Insert picture description here
Insert picture description here
Analysis of the idea of the tree (portal) outside the school gate :
The main idea of this question is very easy to understand. In fact, it is a simulated question combining intervals. Because the data range is relatively small, it is OK to solve it violently.

Two ideas are provided here:

The first type: there is not much explanation for violent solution, just do it in one interval, the time complexity is O(L * M)
AC code:

#include <iostream>

using namespace std;

const int N = 10010;

int L,M;
bool st[N];

int main() {
    
    
    cin >> L >> M;
    for(int i = 0;i<=L;i++)
        st[i] = true;
    while(M--) {
    
    
        int r,l;
        cin >> r >> l;
        for(int i = r ;i <= l;i++)
            st[i] = false;
    }
    int res = 0;
    for(int i = 0;i<=L;i++)
        res += st[i];
    cout << res << endl;
    return 0;
}

The second type: interval merge algorithm, the time complexity is all sorting, O(nlogn)
Insert picture description here
AC code:

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 110;

int m,n;   // m 代表马路长度, n 代表组数

// 结构体 存区间
struct Segment {
    
    
    int l, r;

    // 将结构体 按照左端点进行排序
    bool operator<(const Segment &t) const {
    
    
        return l < t.l;
    }
} seg[N];

int main() {
    
    
    cin >> m >> n;
    for (int i = 0; i < n; i++)
        cin >> seg[i].l >> seg[i].r;
    sort(seg, seg + n);
    int sum = 0;

    // 区间合并代码
    int L = seg[0].l, R = seg[0].r;
    for (int i = 1; i < n; i++) {
    
    
        if (seg[i].l <= R) {
    
    
            R = max(R, seg[i].r);
        } else {
    
    
            sum += R - L + 1;
            L = seg[i].l;
            R = seg[i].r;
        }
    }

    sum += R - L + 1;
    cout << m + 1 - sum << endl;
}

Guess you like

Origin blog.csdn.net/qq_45654671/article/details/112980493