清华大学机试 剩下的树 Easy *贪心的区间思想

基本思想:

自己想到了贪心区间里面进行区间排序的思想;

但是还有一种更简单的,直接进行构建一个标记数组,然后按个数进行标记即可;

关键点:

注意区间包含问题;

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;

struct node {
    int st;
    int ed;
};

int n, m;

vector<node>vec;
vector<node>res;

bool cmp(node a, node b) {
    return a.st < b.st;
}

int main() {
    while (cin>>n>>m){
        node no;
        for (int i = 0; i < m; i++) {
            cin >> no.st >> no.ed;
            vec.push_back(no);
        }
        sort(vec.begin(), vec.end(), cmp);
        int s = vec[0].st;
        int e = vec[0].ed;
        for (int i = 1; i < vec.size(); i++) {
            if (vec[i].st <= e&&vec[i].ed>e) {
                //可以进行衔接;
                e = vec[i].ed;
            }
            else if(vec[i].st>e){
                //不可以进行衔接;
                no.st = s;
                no.ed = e;
                res.push_back(no);
                s = vec[i].st;
                e = vec[i].ed;
            }
        }
        //装入最后的节点;
        no.st = s;
        no.ed = e;
        res.push_back(no);
        //进行数据枚举遍历;
        int cnt = 0;
        for (int i = 0; i < res.size(); i++) {
            cnt += res[i].ed - res[i].st + 1;
        }
        cout << n+1 - cnt << endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/songlinxuan/p/12404307.html