P3045 [USACO12FEB]牛券Cow Coupons 貪心+優先隊列

題目鏈接

貪心思路:

0.貪心撤回

1.首先如果所有的奶牛都使用了優惠券,那麼優惠價格最少的前K個奶牛是必定包含在最終答案中的。如果情況不是這樣,就意味着有一張優惠券用在了K+1到N區間的奶牛上,但是前K個奶牛中的那一個不選,顯然這是不划算的,情況不是最優。

2.考慮全部對排序後的前K個奶牛使用優惠券,再建立一個由小到大保存(P[i]-C[i]) 的堆維護,再對[K+1,N]個奶牛進行選擇時,比較 堆首 <  P[i]-C[i],意思是使得優惠幅度最大,進行更新,然後對這個加上堆首差價,意思是將這張優惠券對第i個奶牛使用。

同時要對[k+1,n]元素進行原始價格排序。

#include <queue>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;

const int MAXN = 50001;
const int INF = 0X3F3F3F3F;

#define lint long long


lint N,K,M;

struct _Cow
{
	int Price;
	int AfterPrice;
}Cow[MAXN];

priority_queue<lint,vector<lint>,greater<lint> > Queue1;

lint ans = 0;

bool cmp1(_Cow a,_Cow b)
{
	return a.AfterPrice < b.AfterPrice;
}

bool cmp2(_Cow a,_Cow b)
{
	return a.Price < b.Price;
}

void Solve(void)
{
	sort(Cow+1,Cow+1+N,cmp1);
	
	lint Sum = 0;
	for(int i = 1;i <= K;i++)
	{
		Sum += Cow[i].AfterPrice;
		if(Sum > M)
		{
			ans = i-1;
			return;
		}
		if(i == N)
		{
			ans = N;
			return;
		}
		Queue1.push(Cow[i].Price-Cow[i].AfterPrice);
	}
	
	sort(Cow+1+K,Cow+1+N,cmp2);
	ans = K;
	for(int i = K+1;i <= N;i++)
	{
		lint MinOff = Queue1.top();
		
		if(MinOff < Cow[i].Price-Cow[i].AfterPrice && !Queue1.empty())    //注意優先隊列是否爲空
		{
			Sum += MinOff;
			Sum += Cow[i].AfterPrice;
			Queue1.pop();
			Queue1.push(Cow[i].Price-Cow[i].AfterPrice);
		}
		else
		{
			Sum += Cow[i].Price;
		}
		if(Sum > M)
		{
			return;
		}
		ans++;
	}
	return;
};

int main(void)
{
	cin >> N >> K >> M;
	for(int i = 1;i <= N;i++)
	{
		cin >> Cow[i].Price >> Cow[i].AfterPrice;
	}
	
	Solve();
	cout << ans << endl;
	
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章