Bitwise knapsack problem

Revision en1, by geronimo00, 2020-04-13 11:43:28

Hi, I need help from CF community regarding this DP problem. I had idea implementing this problem with bitwise subsets, foreach combination -> check max weight.. And can't see what is wrong. My answers are partially correct. (I know that DP solution is better, this is just for fun)

https://atcoder.jp/contests/dp/tasks/dp_d

This is my code and it only works on small numbers.

#include<bits/stdc++.h>
#define vi vector<int>
#include <algorithm>
#include <iterator>
#include <inttypes.h>
#include<iostream>
using ll = long long;
using namespace std;

int main()
{
   long long n,w;
   cin >> n >> w;

   long long a[100][2];
   for(int i=0;i<n;i++){
        cin>>a[i][0] >> a[i][1];

   }
   long long result = 0;

   for(int i=0;i<1<<n;i++){
        long long weightSum = 0;
        long long valueSum = 0;

        for(int j=0;j<n;j++){
            if(i & (1 << j)){
                weightSum+= a[j][0];
                valueSum+= a[j][1];
            }
        }

        if(weightSum <= w){
            result = max(result, valueSum);
        }
   }

   cout << result;

   return 0;
}

Tags dp, #bitwise

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English geronimo00 2020-04-13 11:43:28 1184 Initial revision (published)