poj1456-贪心

题目大意:

有N件商品,分别给出商品的价值和销售的最后期限,只要在最后日期之前销售处,就能得到相应的利润,并且销售该商品需要1天时间。

问销售的最大利润。

解题思路:

1.我用的贪心的思想,将商品的价值从大到小排序,找到销售的最大期限,用hasht数组标记,如果它的期限没有被占用,就在该天销售,如果占用,则从它的前一天开始向前查找有没有空闲的日期,如果有则占用。这样就可以得到最大销售量。

数据不大,竟然没有超时。。。。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define nMax 10010
	
struct Product
{
	int profit;
	int deadline;
}product[nMax];
int n;
bool hash[nMax];
int cmp(const void * a, const void *b)
{
	struct Product *c = (struct Product *)a;
	struct Product *d = (struct Product *)b;
	if (c->profit == d->profit)
	{
		return  c->deadline - d->deadline;
	}
	else
		return d->profit - c->profit;
}
int main()
{
	while (scanf("%d", &n) != EOF)
	{
		memset(hash, false, sizeof(hash));
		for (int i = 0; i < n; ++ i)
		{
			scanf("%d %d", &product[i].profit, &product[i].deadline);
		}
		if (n == 0)
		{
			printf("0\n");
			continue;
		}
		qsort(product, n, sizeof(product[0]), cmp);
		int sum = 0,deadLine;
		for (int i = 0; i < n; ++ i)
		{
			if (!hash[product[i].deadline])
			{
				sum += product[i].profit;
				hash[product[i].deadline] = true;
			}
			else
			{
				int k = product[i].deadline - 1;
				while (k >= 1)
				{
					if (!hash[k])
					{
						sum += product[i].profit;
						hash[k] = true;
						break;
					}
					k --;
				}
			}
		}
		printf("%d\n", sum);
	}
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值