Problem link : https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1071
Solution :
#include<bits/stdc++.h>
using namespace std;
long long int dp[1005][35];
long long int weight[1005];
long long int cost[1005];
long long int cap;
long long int node;
long long int ans=0;
long long int knapsack(long long int idx,long long int w)
{
if(idx==node+1) return 0;
if(dp[idx][w]!=-1) return dp[idx][w];
int profit1=0,profit2=0;
if(w+weight[idx]<=cap) profit1=cost[idx]+knapsack(idx+1,w+weight[idx]);
profit2=knapsack(idx+1,w);
dp[idx][w]=max(profit1,profit2);
return dp[idx][w];
}
int main()
{
long long int t,i,g,p;
cin>>t;
while(t--)
{
cin>>node;
p=node;
i=1;
while(p--)
{
cin>>cost[i]>>weight[i];
i++;
}
cin>>g;
while(g--)
{
memset(dp,-1,sizeof(dp));
cin>>cap;
ans=ans+knapsack(1,0);
}
cout<<ans<<endl;
ans=0;
}
}
Solution :
#include<bits/stdc++.h>
using namespace std;
long long int dp[1005][35];
long long int weight[1005];
long long int cost[1005];
long long int cap;
long long int node;
long long int ans=0;
long long int knapsack(long long int idx,long long int w)
{
if(idx==node+1) return 0;
if(dp[idx][w]!=-1) return dp[idx][w];
int profit1=0,profit2=0;
if(w+weight[idx]<=cap) profit1=cost[idx]+knapsack(idx+1,w+weight[idx]);
profit2=knapsack(idx+1,w);
dp[idx][w]=max(profit1,profit2);
return dp[idx][w];
}
int main()
{
long long int t,i,g,p;
cin>>t;
while(t--)
{
cin>>node;
p=node;
i=1;
while(p--)
{
cin>>cost[i]>>weight[i];
i++;
}
cin>>g;
while(g--)
{
memset(dp,-1,sizeof(dp));
cin>>cap;
ans=ans+knapsack(1,0);
}
cout<<ans<<endl;
ans=0;
}
}
No comments:
Post a Comment