[01] knapsack problem C: herbs
time limit: 1 Sec Memory Limit: 128 MB
subject description
chen was a gifted child, his dream is to become the world's greatest physician. To this end, he wanted to worship in the vicinity of the most prestigious physician as a teacher. Physician in order to determine his qualifications, gave him a problem. Physicians took him to a cave full of herbs says to him:. "Children, this cave has some different herbs, picking each plant requires some time, each plant has its own value and I will give you some time, during this time, you can pick some herbs maximum if you are a smart kid, you should be taken to make the total value of herbs. "
If you are chen, you can accomplish this task ?
Input
first line of input two integers T (1 <= T <= 1000) and M (1 <= M <= 100), separated by a space, and T represents a total time can be used herbs, M the number of herbs cave representatives. Next M lines each comprising two integers between 1 to 100 (including 1 and 100), respectively, represent the value of a strain picked herbs time this strain and herbs.
Output
output includes line, which contains a single integer, said in a specified period of time, it can be taken to the maximum total value of herbs.
Sample input the Copy
70. 3
71 is 100
69. 1
. 1 2
sample output the Copy
. 3
the AC codes:
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
int main()
{
int n,m,B[1000],v[1000],w[1000];
int i,j;
memset(B,0,sizeof(B));/*清零*/
B[0]=0;
scanf("%d %d",&n,&m); /*n为容量,m为物品数*/
for(i=0; i<m; i++)
{
scanf("%d %d",&w[i],&v[i]);
}
for(i=0; i<m; i++)
{
for(j=n; j>=0; j--)
{
if(B[j]<=B[j-w[i]]+v[i] && j-w[i]>=0 )/*更新状态*/
{
B[j]=B[j-w[i]]+v[i];
}
}
}
// for(i=0;i<=n;i++)
// {
// printf("%d ",B[i]); /*测试数据(插桩)*/
// }
printf("%d",B[n]); /*数组第n个值为最优解*/
return 0;
}
This code can be derived only optimal solution can not show all of the optimal solution can not be obtained from the optimum composition that few items, subsequent updates.