动态规划问题 -- 单价不等水果 装入固定容量背包 最大价值问题
从第一个元素依次寻找最大值
背包的容量计数器,从当前选择的元素的大小开始,循环到最大背包容量大小
此时选择的物品的价值 + 剩余空间所能容纳的物品价值总合, 另一个角度看就是此时选择物品的大小 + 剩余宣空间的大小 = 背包总大小
判断新的总价值是否大于当前背包大小容量的价值,大于则更新
sample_input.txt
----------------------------------------------------
1
8 5
6 6700
4 4500
2 2250
1 1100
5 5700
main.c
----------------------------------------------------
#include <stdio.h>
#define MAX_PACKAGE_SIZE 100
//EelSizeValueMap[x][0] -- element x size
//EelSizeValueMap[x][1] -- element x value
int EelSizeValueMap[MAX_PACKAGE_SIZE][2];
int sumValue[MAX_PACKAGE_SIZE];
#define DEBUG
int main(void)
{
int test_case;
int T;
int Total_Capability,Element_Nums;
int size,value;
int i;
int cap_index;
int avali_cap;
int newValue;
/*
freopen function below opens input.txt file in read only mode, and afterward,
the program will read from input.txt file instead of standard(keyboard) input.
To test your program, you may save input data in input.txt file,
and use freopen function to read from the file when using scanf function.
You may remove the comment symbols(//) in the below statement and use it.
But before submission, you must remove the freopen function or rewrite comment symbols(//).
*/
//#ifdef DEBUG
freopen("sample_input.txt", "r", stdin);
//#endif
/*
If you remove the statement below, your program's output may not be recorded
when your program is aborted due to the time limit.
For safety, please use setbuf(stdout, NULL); statement.
*/
setbuf(stdout, NULL);
scanf("%d", &T);
for( test_case = 1; test_case <= T; test_case ++ )
{
scanf("%d %d",&Total_Capability,&Element_Nums);
//clear EelSizeValueMap map data
for(i = 0; i<Total_Capability+2; i++)
{
EelSizeValueMap[i][0] = EelSizeValueMap[i][1] = 0;
sumValue[i] = 0;
}
for(i = 0; i<Element_Nums; i++)
{
scanf("%d %d",&size, &value);
EelSizeValueMap[i][0] = size;
EelSizeValueMap[i][1] = value;
}
//从第一个元素依次寻找最大值
for(i = 0; i<Element_Nums; i++)
{
//背包的容量计数器,从当前选择的元素的大小开始,循环到最大背包容量大小
for(cap_index = EelSizeValueMap[i][0]; cap_index <= Total_Capability; cap_index++)
{
//当前背包空间剩余大小
avali_cap = cap_index - EelSizeValueMap[i][0];
//此时选择的物品的价值 + 剩余空间所能容纳的物品价值总合, 另一个角度看就是此时选择物品的大小 + 剩余宣空间的大小 = 背包总大小
newValue = sumValue[avali_cap] + EelSizeValueMap[i][1];
//printf("i=%d cap_index=%d avali_cap=%d sumValue[%d]=%d sumValue[%d]=%d EelSizeValueMap[%d][1]=%d newValue=%d\n",i,cap_index,avali_cap,avali_cap,sumValue[avali_cap],cap_index,sumValue[cap_index],i,EelSizeValueMap[i][1],newValue);
//判断新的总价值是否大于当前背包大小容量的价值
if( newValue > sumValue[cap_index] )
{
sumValue[cap_index] = newValue;
//item[cap_index] = i;
}
}
}
printf("#test_case %d Max_price %d\n",test_case,sumValue[Total_Capability]);
}
return 0;
}