nafeeur10's blog

By nafeeur10, history, 9 years ago, In English

We know in 0-1 Knapsack problem we get the maximum benefits from some items with a limited capacity. Example:

4 10 // 5 items, 10 capacity
1 120 // weight cost_value
4 280
3 150
4 200
Ans: 600
Total Weight: 9

But my question is, I want the total weight and benefit at a time. How is this possible? And what will be the change of my code? Please suggest me with my own code.

#include <bits/stdc++.h>

using namespace std;

#define MAX_N 100
#define MAX_W 1000
int n;
int dp[MAX_N+1][MAX_W+1];
int weight[MAX_N+1];
int cost[MAX_N+1];
int CAP;
int func(int i,int w)
{
    if(i==n+1) return 0;
    if(dp[i][w]!=-1) return dp[i][w];
    int profit1=0,profit2=0;
    if(w+weight[i]<=CAP)
        profit1=cost[i]+func(i+1,w+weight[i]);

    profit2=func(i+1,w);
    dp[i][w]=max(profit1,profit2);
    return dp[i][w];
}
int main()
{

    //freopen("in","r",stdin);
    memset(dp,-1,sizeof(dp));
    scanf("%d%d",&n,&CAP);
    for(int i=1; i<=n; i++)
    {
        scanf("%d %d",&weight[i],&cost[i]);
    }
    printf("%d\n",func(1,0));


}

Full text and comments »

  • Vote: I like it
  • +7
  • Vote: I do not like it

By nafeeur10, 9 years ago, In English

I'm learning dynamic Programming (DP). I have already learned 0-1 Knapsack, Coin Change and LIS. I want to solve some problems on these categories. Please suggest me some problems of codeforces those are solvable by these 3 algorithms.

Full text and comments »

  • Vote: I like it
  • +11
  • Vote: I do not like it

By nafeeur10, 10 years ago, In English

Coin Change(III) I want to solve it by three state coin change DP. But I am getting MLE, RTE. How can I solve it by this way?? Please help me. My code is here.

#include <bits/stdc++.h>

using namespace std;

int n,m,dp[101][101][1001];
int coin[101], number_coin[101];
set<int>S;
int M;

int call(int i, int taken_i, int make)
{
    if(make>=1 && make<=M) S.insert(make);
    if(make>M || i>n) return 0;
    if(make==M) return 1;

    if(dp[i][taken_i][make]!=-1)
        return dp[i][taken_i][make];
    int p1=0, p2=0;
    if(taken_i>0)
    {
        p1=call(i,taken_i-1,make+coin[i]);
    }
    p2=call(i+1,number_coin[i+1], make);
    dp[i][taken_i][make]=p1+p2;
    //cout<<dp[i][taken_i][make]<<endl;
    return dp[i][taken_i][make];
}

int main()
{
    int t;
    scanf("%d",&t);
    int cas=0;
    while(t--)
    {
        scanf("%d %d",&n, &m);
        M=m;
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&coin[i]);
        }
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&number_coin[i]);
        }

        memset(dp,-1,sizeof(dp));
        int a=call(1,number_coin[1],0);
        printf("Case %d: %d\n",++cas,S.size());
        S.clear();
    }
    return 0;
}

Full text and comments »

  • Vote: I like it
  • +5
  • Vote: I do not like it