1. 程式人生 >實用技巧 >其它 >YbtOJ 資料結構課堂過關 例4 工作安排【小根堆】【反悔貪心】

YbtOJ 資料結構課堂過關 例4 工作安排【小根堆】【反悔貪心】


YbtOJ 資料結構課堂過關 例4 工作安排【小根堆】【反悔貪心】


思路

這道題我一開始想到一個憨批做法在YbtOJ上過了正當我沾沾自喜的時候——

YbtOJ 資料結構課堂過關 例4 工作安排【小根堆】【反悔貪心】

實際上正解是:
考慮貪心,如果當前工作可選,那麼就把它加入要做行列中,否則就在要做的堆中選擇一個利潤最小的(堆頭)踢出。

程式碼

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
long long n,ans,c;
priority_queue<long long> q;
struct node
{
	int d,p;
}a[100010];
bool cmp(const node&x,const node&y)
{
	return x.d<y.d;
}
int main()
{
	cin>>n;
	for(int i=1; i<=n; i++)
	   scanf("%lld%lld",&a[i].d,&a[i].p);
	sort(a+1,a+1+n,cmp);
	for(int i=1; i<=n; i++)
	 {
	 	q.push(-a[i].p);
	 	c++;
	 	if(c>a[i].d)
	 	 {
	 	 	q.pop();
	 	 	c--;
		 }
	 }
	while(!q.empty())
	  ans-=q.top(),q.pop();
	cout<<ans;
	return 0;
}