题解 SP11515 【BUSYMAN - I AM VERY BUSY】

其实CF也有类似的一道题

本题看起来像是DP,但这种做多了就知道典型贪心

我结合了运算符重载做

既然要参加的多,结束时间就应该小

定义一个类,两个成员变量start和end,一个成员函数operator <

主函数sort一下(对于已经重载过小于号的类,不需要cmp,但必须提交C++11或以上,SPOJ的c++会CE)

代码,170ms:

#include <iostream>
#include <algorithm>
using namespace std;

class Node
{
    public:
        int start, end;
        bool operator <(const Node &x) const
        {
            return end < x.end;
        }
};

Node a[100005];

int main()
{
    int T;
    cin >> T;
    for(int i = 1; i <= T; i++)
    {
        int n;
        cin >> n;
        for(int j = 1; j <= n; j++)
        {
            cin >> a[j].start >> a[j].end;
        }
        sort(a + 1, a + n + 1);
        int ans = 1, now = a[1].end;
        for(int j = 2; j <= n; j++)
        {
            if(a[j].start >= now)
            {
                now = a[j].end;
                ans++;
            }
        }
        cout << ans << endl;
    }
    return 0;
}

开点常数优化(不喜勿喷),只用了70ms!!!

#include <iostream>
#include <algorithm>
using namespace std;

class Node
{
    public:
        int start, end;
        inline bool operator <(const Node &x) const
        {
            return end < x.end;
        }
};

Node a[100005];

int main()
{
    ios::sync_with_stdio(false);
    int T;
    cin >> T;
    for(register int i = 1; i <= T; i++)
    {
        int n;
        cin >> n;
        for(register int j = 1; j <= n; j++)
        {
            cin >> a[j].start >> a[j].end;
        }
        sort(a + 1, a + n + 1);
        int ans = 1, now = a[1].end;
        for(register int j = 2; j <= n; j++)
        {
            if(a[j].start >= now)
            {
                now = a[j].end;
                ans++;
            }
        }
        cout << ans << endl;
    }
    return 0;
}

求过

posted @ 2020-11-14 21:15  HappyBobb  阅读(15)  评论(0)    收藏  举报  来源