Supermarket POJ-1456(并查集)

超市里有N个商品. 第i个商品必须在保质期(第di天)之前卖掉, 若卖掉可让超市获得pi的利润.

每天只能卖一个商品.

现在你要让超市获得最大的利润. Input多组数据.

每组数据第一行为一个整数N (0 <= N <= 10000), 即超市的商品数目

之后N行各有两个整数, 第i行为 pi, di (1 <= pi, di <= 10000)Output对于每一组数据, 输出当前条件下超市的最大利润
Sample Input
4
50 2
10 1
20 2
30 1
7
20 1
2 1
10 3
100 2
8 2
5 20
50 10
Sample Output
80
185
Hint
Translated by shleodai

#include<iostream>
#include<cstring>
#include<algorithm>
#define MAX 10010
using namespace std;
int f[MAX];
struct market{
int qi;
int di;
}m[MAX];//定义一下商品的钱数和天数

int cmp(market a,market b)
{
return a.qi>b.qi;//按价格排序
}
int root(int x)//寻找根结点
{
if(f[x]==-1)
return x;
else
{
	f[x]=root(f[x]);
	return f[x];
}
}
int main()
{
int n;
while(cin>>n)
{
	memset(f,-1,sizeof(f));//把f中元素置为-1
	for(int i=0;i<n;i++)
	{
		cin>>m[i].qi>>m[i].di;
	}
	sort(m,m+n,cmp);//排序
	int sum=0;
	for(int i=0;i<n;i++)
	{
		int temp=root(m[i].di);//返回m[i].di或它的根
		if(temp>0)//如果天数没有被占用
		{
			sum+=m[i].qi;
			f[temp]=temp-1;//第temp天被占用,f[temp]要等于temp-1
		}
	}
	cout<<sum<<"\n";
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值