/*OJ.h*/
#ifndef __OJ_H__
#define __OJ_H__
typedef struct paperInfo
{
int costTime;
int value;
double valuePerTime;
}paperInfo;
int GetMaxValue(int nPapers, int nRemain, int paper[][2], double* pMaxValue);
#endif
<pre name="code" class="cpp">#include "OJ.h"
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(const paperInfo &a, const paperInfo &b)
{
return a.valuePerTime > b.valuePerTime ? true:false;
}
/*
输入: nPapers表示试卷的数目(1≤Papers≤20),nRemain表示剩余的时间(1≤nRemain≤10000),paper[][2]是一个Papers*2的数组,
每一行的两个元素依次为做完这一份试卷所需的时间、做完这份试卷的价值
输出: *pMaxValue为获得的最大价值
返回:
0:异常
1:计算成功返回
*/
int GetMaxValue(int nPapers, int nRemain, int paper[][2], double* pMaxValue)
{
*pMaxValue = 0;
paperInfo *array = new paperInfo [nPapers];
memset(array, 0, sizeof(paperInfo) * nPapers);
for (int i = 0; i < nPapers; ++i)
{
array[i].costTime = paper[i][0];
array[i].value = paper[i][1];
array[i].valuePerTime = double(paper[i][1])/paper[i][0];
}
sort(array, array + nPapers, cmp);
for (int i =0; i < nPapers; ++i)
{
if (nRemain >= array[i].costTime)
{
*pMaxValue += double(array[i].value);
nRemain -= array[i].costTime;
}
else
{
*pMaxValue += array[i].valuePerTime * nRemain;
nRemain = 0;
}
if (nRemain <= 0)
{
break;
}
}
return 0;
}