【POJ 1456】Supermarket【并查集】

题目大意:

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


思路:

这道题可以用贪心做。因为保质期前都可以卖,所以为了答案最有,就尽量将商品晚卖一些(即最后一天再卖)。就可以保证能卖出的价值最大。证明就不证了,很显而易见。
还可以用并查集做。设father[i]father[i]表示保质期在第ii天的商品必须在第father[i]father[i]天前卖完。(因为可能第ii天卖另外一个商品,就必须推前卖),那么初始化为father[i]=1father[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;
}
原文地址:https://www.cnblogs.com/hello-tomorrow/p/11998665.html