Topic: Knapsack
Solution:
#include<bits/stdc++.h>
using namespace std;
int wt[12345], val[12345];
int Knapsack(int w, int wt[], int val[], int n)
{
int k[n+1][w+1];
for(int i = 0; i <= n; i++)
{
for(int j = 0; j <= w; j++)
{
if(i == 0 || j == 0)k[i][j] = 0;
else if(wt[i-1] <= j)
k[i][j] = max(val[i-1]+k[i-1][j-wt[i-1]], k[i-1][j]);
else k[i][j] = k[i-1][j];
}
}
return k[n][w];
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
memset(val, 0, sizeof(val));
memset(wt, 0, sizeof(wt));
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
scanf("%d%d",&val[i], &wt[i]);
}
int k,W;
scanf("%d",&k);
int ans =0;
while(k--)
{
int x;
scanf("%d",&x);
ans += Knapsack(x, wt, val, n);
}
printf("%d\n", ans);
}
return 0;
}
No comments:
Post a Comment