Question meaning: After school, WNJXYK is going to bring some books back. He has N books and the capacity of the school bag is C. (1 ≤ N ≤ 100000, 1 ≤ C ≤ 10000)
Each book has a corresponding value Vi and a capacity Ci to be occupied. Now I ask you how many books of value WNJXYK can bring back? (0 ≤ Vi , Ci ≤ 10)
If you directly use the 01 backpack, it will be timed out. Also note that there are multiple sets of inputs here.
Then, after reading other people's solutions, I know that converting this 01 backpack into multiple backpacks can reduce the time complexity. Because here ci and vi obviously give a very wide range. is small, and the range of n is very large, indicating that there must be many duplicate books, so we record the number of each kind of books, and use multiple knapsacks to solve....
Post a big guy template
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
int dp[1000000];
int wupin[11][11];
int v,n;
void zoreonepack(int val,int cost)
{
for(int i=v;i>=cost;i--)
{
if(dp[i-cost]+val>dp[i])
{
dp[i]=dp[i-cost]+val;
}
}
}
void completepack(int val,int cost)
{
for(int i=cost;i<=v;i++)
{
dp[i]=max(dp[i],dp[i-cost]+val);
}
}
void multipack(int val,int cost,int num)
{
if(num*cost>=v)
{
completepack(val,cost);
}
else
{
int k=1;
while(k<num)
{
zoreonepack(k*val,k*cost);
num-=k;k+=k;
}
zoreonepack(num*val,num*cost);
}
}
int main()
{
while(~scanf("%d%d",&n,&v))
{
memset(dp,0,sizeof(dp));
memset(wupin,0,sizeof(wupin));
for(int i=0;i<n;i++)
{
char s[1000];
int x,y;
scanf("%s%d%d",s,&x,&y);
wupin[x][y]++;
}
for(int i=0;i<11;i++)
{
for(int j=0;j<11;j++)
{
if(wupin[i][j]!=0)
{
multipack(i,j,wupin[i][j]);
}
}
}
printf("%d\n",dp[v]);
}
}