Here you will find solutions of many problems on spoj. If you want solution of some problem which is not listed in blog or have doubt regarding any spoj problem (which i have solved) or any programming concept (data structure) you can mail me @ raj.nishant360@gmail.com

And my humble request to you all that don't copy the code only try to understand the logic and algorithm behind the code. I have started this because if you tried as hard as you can and still can't find any solution to the problem then you can refer to this.
You can read my answer how to start competitive programming CLICK HERE

Tuesday, March 11, 2014

LKS - Large Knapsack

LKS - Large Knapsack (link to the question)

can be implemented by using 0/1 knapsack with little bit modification since in each iteration two consecutive 
row are being used one is in read mode and another in write mode. Since the array could exceed the limit that why i did this modification... 
#include<stdio.h>
#define max(x,y) (x>y)?x:y;

int arr[2][2000001]={0};

struct node
{
    int value;
    int weight;
}obj[501];


int main()
{
    int i,j,n,W,k;

    scanf("%i%i",&W,&n);

    i=0;
    while(++i <= n)
        scanf("%i%i",&obj[i].value,&obj[i].weight);

    i=0;
    while(++i <= n)
    {
        j = 0;

        if(i%2)
        {
            while(++j <= W)
            {
                if(obj[i].weight <= j)
                    arr[1][j] = max( obj[i].value + arr[0][ j-obj[i].weight ] , arr[0][j] )
                else
                    arr[1][j] = arr[0][j];
            }

        }

        else
        {
            while(++j <= W)
            {
                if(obj[i].weight <= j)
                    arr[0][j] = max( obj[i].value + arr[1][ j-obj[i].weight ] , arr[1][j] )
                else
                    arr[0][j] = arr[1][j];
            }
        }
    }


    if(n&1)
        printf("%i\n",arr[1][W]);
    else
        printf("%i\n",arr[0][W]);

    return 0;
}



No comments:

Post a Comment

Your comment is valuable to us