For example, consider the products Prod={a,b,c,d} with (pa,da)=(50,2), (pb,db)=(10,1), (pc,dc)=(20,2), and (pd,dd)=(30,1). The possible selling schedules are listed in table 1. For instance, the schedule Sell={d,a} shows that the selling of product d starts at time 0 and ends at time 1, while the selling of product a starts at time 1 and ends at time 2. Each of these products is sold by its deadline. Sell is the optimal schedule and its profit is 80.
Write a program that reads sets of products from an input text file and computes the profit of an optimal selling schedule for each set of products.
4 50 2 10 1 20 2 30 1 7 20 1 2 1 10 3 100 2 8 2 5 20 50 10Sample Output
80 185Hint
题意:给出物品需要卖出的最后期限以及收益,求出每天卖出什么物品可以获得最大利润,并输出;
分析:很容易想到排序,,至于怎么排序,根据题意很容易知道,难点就是今天没卖出去的,还可以前几天卖出,这话听起来不对,但却是这道题的关键,我们按照天数从大到小排序,辅排利润
代码如下:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int book[10005];
struct node
{
int p;
int d;
}shc[10005];
int n;
bool cmp(const node &a,const node &b)
{
if(a.d!=b.d) return a.d>b.d;
else if(a.p!=b.p) return a.p>b.p;
else return 0;
}
int main()
{
int i,j,res,k,maxx,ans;
while(scanf("%d",&n)!=EOF)
{
memset(book,0,sizeof(book));
for(i=0;i<n;i++)
scanf("%d %d",&shc[i].p,&shc[i].d);
sort(shc,shc+n,cmp);
res=0;
ans=shc[0].d;
for(j=ans;j>=1;j--)//按照天数倒数排序
{
maxx=0;
for(i=0;i<n;i++)每次循环一次
{
if(shc[i].d>=j&&book[i]==0)
{
if(shc[i].p>maxx)
{
maxx=shc[i].p;
k=i;
}
}
}
book[k]=1;
res=res+maxx;
}
printf("%d\n",res);
}
return 0;
}