不相交区间数

版权声明:欢迎转载!拒绝抄袭. https://blog.csdn.net/qq_36257146/article/details/89814639
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

struct Node
{
    int be;
    int ed;
    Node(int a,int b):be(a),ed(b) {}
    const bool operator < (const Node & b) const
    {
        if(ed == b.ed)
        {
            return be<b.be;
        }
        else return ed<b.ed;
    }
};

vector<Node>nodes;

bool connect(int i,int j)
{
    int a1 = max(nodes[i].be,nodes[i].ed);
    int a2 = min(nodes[j].be,nodes[j].ed);
    return a1>=a2;
}

int main()
{
    int T,n;
    int a,b;
    cin>>T;
    while(T--)
    {
        cin>>n;
        nodes.clear();
        for(int i = 0; i<n; i++)
        {
            cin>>a>>b;
            nodes.push_back(Node(a,b));
        }
        sort(nodes.begin(),nodes.end());

        int ans = 1;
        int i = 1;
        int last = 0;
        while(i<n)
        {
            if(connect(0,i))
            {
                i++;
                continue;
            }
            if(!connect(last,i))
            {
                ans++;
                last = i;
            }
            i++;
        }
        cout<<ans<<endl;
    }
    return 0;
}
/**
2
2
1 10
10 11
3
1 10
10 11
11 20

**/

猜你喜欢

转载自blog.csdn.net/qq_36257146/article/details/89814639