贪心算法

1 活动安排问题

#include <iostream>
#include <vector> // vector
#include <iterator> //ostream_iterator
#include <algorithm> //stable_sort

using namespace std;

// 活动信息
class Activity
{
public:
    Activity(int beg, int end)
    {
        m_tEnd = end;
        m_tBegin = beg;
        m_tShow = true;
    }

    friend bool operator < (const Activity & a,const Activity &b)
    {
        return a.m_tEnd < b.m_tEnd;
    }

    bool operator >= (const Activity & b)
    {
        return this->m_tBegin >= b.m_tEnd;
    }

    friend ostream & operator << (ostream & out, const Activity & act){

        if ( act.m_tShow == true)
        {
            out << act.m_tBegin << " " << act.m_tEnd << endl;
        }

        return out;
    }

private:
    int m_tEnd;
    int m_tBegin;
    bool m_tShow;   //是否被安排

public:
    friend class Arrange;   //友元类,可以更改本类属性
};

//活动安排类
class Arrange
{
public:
    Arrange(vector<Activity> &actVec){
        m_actVec = actVec;
    }

    void arrangeActivity()
    {
        // 按照结束时间早晚排序
        _sortWithEnd();

        auto comp = m_actVec.begin();

        for (auto it = m_actVec.begin()+1; it != m_actVec.end(); it++)
        {
            if (*it >= *comp) 
            {
                comp = it;
            }
            else
                it->m_tShow = false;
        }

        // 输出
        copy(m_actVec.begin(), m_actVec.end(), ostream_iterator<Activity>(cout, ""));
    }

private:
    vector<Activity> m_actVec;

private:
    void _sortWithEnd()
    {
        stable_sort(m_actVec.begin(), m_actVec.end());
// copy(m_actVec.begin(), m_actVec.end(), ostream_iterator<Activity>(cout,""));
    }
};

int main()
{
    vector<Activity> actVec;

    actVec.push_back(Activity(1, 4));
    actVec.push_back(Activity(3, 5));
    actVec.push_back(Activity(0, 6));
    actVec.push_back(Activity(5, 7));
    actVec.push_back(Activity(3, 8));
    actVec.push_back(Activity(5, 9));
    actVec.push_back(Activity(6, 10));
    actVec.push_back(Activity(8, 11));
    actVec.push_back(Activity(8, 12));
    actVec.push_back(Activity(2, 13));
    actVec.push_back(Activity(12, 14));

    Arrange arr(actVec);
    arr.arrangeActivity();

    return 0;
}

你可能感兴趣的:(贪心算法)