左神算法学习日记——堆(二)

#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<time.h>
#include<queue>
#include<algorithm>
#include<xfunctional>
using namespace std;

class project
{
public:
	int cost;
	int profit;
	project() = default;
	project(int c, int p)
	{
		cost = c;
		profit = p;
	}
	project(const project& p)//push进堆时用到了拷贝构造函数,虽然不写也无所谓
	{
		cost = p.cost;
		profit = p.profit;
	}
	project& operator = (const project& p)
	{
        if(this!=&p)
		{cost = p.cost;
		profit = p.profit;}
        return *this;
	}
};

struct co//以cost为基准建立小根堆
{
	bool operator()(project& _Left, project& _Right)
	{
		return (_Left.cost > _Right.cost);
	}
};

struct _pr//以cost为基准建立大根堆
{
	bool operator()(project& _Left, project& _Right)
	{
		return (_Left.profit < _Right.profit);
	}
};

int main()
{
	vector<int> costs = { 1, 2, 5 };
	vector<int> profits = { 4, 3, 7 };
	int k = 2, m = 3;
	vector<project> pro;
	for (int i = 0; i < costs.size(); i++)
	{
		pro.push_back(project(costs[i], profits[i]));
	}
	priority_queue<project, vector<project>, co> small;
	priority_queue<project, vector<project>, _pr> big;//贪心策略,可以随时随地push并得到最大
                                                           //值
	for (int i = 0; i < pro.size(); i++)
	{
		small.push(pro[i]);
	}
	while (k>0)
	{
		while (!small.empty() && small.top().cost < m)
		{
			big.push(small.top());
			small.pop();
		}
		m += big.top().profit;
		big.pop();
		k--;
	}
	cout << m;
}

猜你喜欢

转载自blog.csdn.net/w275412237/article/details/89359706
今日推荐