Supermarket poj1456

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MrTinTin/article/details/83378486

题目大意是买卖N件东西,每件东西都有个截止时间,在截止时间之前买都可以,而每个单位时间只能买一件。问最大获利。

解法一:

按过期时间排序,从前向后一个个考虑,以商品利润为权值建立一个小根堆,初始为空。

1,若当前商品的过期时间小于等于堆得大小,则说明在前t天已经排满,则比较堆顶元素和当前商品利润,考虑是否替换。

2,若大于,则直接加入堆。

最后堆中的商品就是要卖的商品。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#define f(i,l,r) for(i=(l);i<=(r);i++)
using namespace std;
const int MAXN=10005;
struct Node{
	int p,d;
	bool operator < (const Node& tmp)const{
		return p>tmp.p;
	}
}a[MAXN];
priority_queue<Node> q;
int n;
bool cmp(Node a,Node b)
{
	return a.d<b.d;
}
int main()
{
	int i,j,ans;
	while(~scanf("%d",&n)){
		ans=0;
		f(i,1,n){
			cin>>a[i].p>>a[i].d;
		}
		sort(a+1,a+1+n,cmp);
		q.push(a[1]);
		f(i,2,n){
			int u=q.top().p;
			if(a[i].d>q.size()){
				q.push(a[i]);
			}
			else if(a[i].p>u){
				q.pop();
				q.push(a[i]);
			}
		}
		while(!q.empty()){
			ans+=q.top().p;
			q.pop();
		}
		cout<<ans<<endl;
	}
	return 0;
}

解法二:优先考虑利润大的商品,对每个商品,尽量晚的卖出。

如果当天可以卖的话,就拿一天卖掉,如果有商品占了那一天,就往前一天寻找,并查集在这里就作为最靠近其保质期当天的那一天,如果其根为0,则表示该商品没有空闲的天卖出。

#include<cstdio>
#include<algorithm>
#include<iostream>
#define f(i,l,r) for(i=(l);i<=(r);i++)
using namespace std;
const int MAXN=10005;
int n,m;
struct Node{
	int p,d;
	bool operator < (const Node& tmp)const{
		return p>tmp.p;
	}
}a[MAXN];
int fa[MAXN];
inline void Makeset()
{
	int i;
	f(i,1,m) fa[i]=i;
}
inline int Find(int x)
{
	return fa[x]==x?x:fa[x]=Find(fa[x]);
}
inline void Union(int x,int y)
{
	x=Find(x);y=Find(y);
	fa[x]=y;
}
int main()
{
//	ios::sync_with_stdio(false);
	int i,j,ans;
	while(~scanf("%d",&n)){
		ans=0;
		f(i,1,n){
			cin>>a[i].p>>a[i].d;
			m=max(m,a[i].d);
		}
		Makeset();
		sort(a+1,a+1+n);
		f(i,1,n){
			int pos=Find(a[i].d);
			if(pos==0) continue;
			ans+=a[i].p;
			Union(pos,pos-1);
		}
		cout<<ans<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/MrTinTin/article/details/83378486