POJ - 1456 基础并查集+贪心

考虑这样一个贪心策略,利润大的物品肯定要有较高的优先级,我们先把商品按利润排序,每个商品 肯定只能在 1到di-1这其中的一个时间点卖出,我们可以用并查集维护每个商品能卖出的最左时间点 当一个商品在当前时间点 t 卖出,那么t这个位置就被占据了,我们得合并t 和 t-1  并把t-1作为t的根,这样对于下一个在t点的商品,它只要根据get操作 找到最左卖出的时间点并且占据它就行(把这个商品的利润计入答案) 如果这个时间点为0 说明1到di-1这些时间都被占据了 这个商品必定不能卖出 不需要管

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
struct shop{
	int p,d;
	bool operator < (const shop& a)const{
		return p>a.p;
	}
}s[10020];
int fa[10020],n;
void init(){
	for(int i = 1; i <= 10000; i++) fa[i]=i;
}
int getfa(int x){
	return x==fa[x]?x:fa[x]=getfa(fa[x]);
}
void unite(int x,int y){
	x=getfa(x),y=getfa(y);
	if(x!=y) fa[x]=y;
}
int main(){
	while(~scanf("%d",&n)){
		init();
		for(int i = 1; i <= n; i++) scanf("%d%d",&s[i].p,&s[i].d);
		sort(s+1,s+1+n);
		int ans = 0;
		for(int i = 1; i <= n; i++){
			int f = getfa(s[i].d);
			//printf("p=%d d=%d f=%d\n",s[i].p,s[i].d,f);
			if(f){
				ans+=s[i].p;
				unite(f,f-1);
			}
		} 
		printf("%d\n",ans);
	}
	return 0;
}

优先队列做法:https://blog.csdn.net/weixin_43824564/article/details/97611629

原创文章 85 获赞 103 访问量 2485

猜你喜欢

转载自blog.csdn.net/weixin_43824564/article/details/105864645