题目大意:
有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;
}