选择不相交区间

来源:互联网 发布:上海大数据产业联盟 编辑:程序博客网 时间:2024/05/29 02:38

贪心思想

根据每个区间的结束点进行排序,然后进行更新

#include <iostream>#include <algorithm>using namespace std;struct Point{    int x, y;    bool operator<(const Point s) const    {        return y < s.y;    }}A[1002];int main() {    int t,n,cnt,end;    cin >> t;    while (t--)    {        cnt = 0;        end = -1;        cin >> n;        for (int i = 0; i < n; i++)            cin >> A[i].x >> A[i].y;        sort(A, A + n);        for (int i = 0; i < n; i++)        {            if (end < A[i].x)//如果下一个区间起始点比上一个区间终点大则更新            {                cnt++;                end = A[i].y;            }        }        cout << cnt << endl;    }    return 0;}
原创粉丝点击