【POJ 1456】Supermarket【并查集】

题目大意:

题目链接:http://poj.org/problem?id=1456
每个商品都有保质期和价值,每天只能卖出一个商品。求能卖出的最大价值。


思路:

这道题可以用贪心做。因为保质期前都可以卖,所以为了答案最有,就尽量将商品晚卖一些(即最后一天再卖)。就可以保证能卖出的价值最大。证明就不证了,很显而易见。
还可以用并查集做。设 f a t h e r [ i ] father[i] father[i]表示保质期在第 i i i天的商品必须在第 f a t h e r [ i ] father[i] father[i]天前卖完。(因为可能第 i i i天卖另外一个商品,就必须推前卖),那么初始化为 f a t h e r [ i ] = − 1 father[i]=-1 father[i]=1,保证不会出错。


代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;

int n,father[10001],sum;

struct node
{
	int day,p;  //分别表示保质期和价格
}a[10001];

bool cmp(node x,node y)
{
	return x.p>y.p;
}

int find(int x)  
{
	if (father[x]<0) return x;  //可以不用再往前了
	return father[x]=find(father[x]);
}

int main()
{
	while (cin>>n)
	{
		memset(father,-1,sizeof(father));
		for (int i=1;i<=n;i++)
		 scanf("%d%d",&a[i].p,&a[i].day);
		sort(a+1,a+1+n,cmp);  //按照价格排序
		for (int i=1;i<=n;i++)
		{
			int day=find(a[i].day);  //能卖的最后一天
			if (day>0)
			{
				father[day]=day-1;  //这天卖这个商品
				sum+=a[i].p;
			}
		}
		printf("%d\n",sum);
		sum=0;
	}
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值