I am trying to write a recursive code for the problem : Minimum number of jumps. Problem Link
This is the code that I have currently written. This code does not cover all the test cases. I wanted to know where I was going wrong with the code. I have made the recursive tree in my notebook for a sample array.
int solve(const int arr[], const int &n, int idx, int steps, bool &found){
if(arr[idx] == 0) return INT_MAX;
if(idx >= n - 1) {
found = true;
return steps;
}
int res = INT_MAX;
int lim = min(idx+arr[idx], n-1);
for(int i=1; i<=lim; i++) {
if(idx+i <= n) {
int ans = solve(arr, n, idx + i,steps + 1, found);
res = min(res, ans);
}
}
return res;
}
int minJumps(int arr[], int n){
bool found = false;
int res = solve(arr, n, 0, 0, found);
if(!found) return -1;
return res;
}
The code works for some cases like :
arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
but not for other arrays like:
arr[] = {1, 5, 4, 2, 0, 4, 0, 1, 1, 1, 3, 2, 1, 0, 3, 2, 1, 2, 0, 0, 1}
The expected output for this is -1, but my function returns 4.
I have spent over 4 hours trying to figure this out. I was thinking maybe some of you can help me.
I am NOT trying to get the solution to get accepted, I just want to first create a correct recursive code, which I can then memoize and then convert it to Dynamic Programming code.
UPDATE:
I may have fixed the code, can anyone please help me in verifying its correctness? I plan on converting this to DP code.
Here is the updated code:
int solve(const int arr[], const int &n, int idx, int steps){
if(idx <= n - 1 && arr[idx] == 0) return INT_MAX;
if(idx >= n - 1) return steps;
int res = INT_MAX;
for(int i=1; i<=arr[idx]; i++) {
if(idx+i <= n) {
int ans = solve(arr, n, idx + i,steps + 1);
res = min(res, ans);
}
}
return res;
}
int minJumps(int arr[], int n){
int res = solve(arr, n, 0, 0);
if(res == INT_MAX) return -1;
return res;
}
Related
I'm working through this problem: https://leetcode.com/problems/pacific-atlantic-water-flow/
After battling through my own solution for several hours, I ended up not being able to fully solve it, so I'm tracing through how others did it. My new code is based on this: https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/608490/C%2B%2B-Implementation-(DFS)
It's basically the same, except I made it more verbose, and I added some comments for clarity. Even though the code is virtually the same, I'm getting a heap overflow error for very large inputs. I'm not sure what's causing it, but I'm guessing that I'm not correctly passing references to vectors and end up making copies in memory. Can someone please help me figure out the inefficiency?
#include <vector>
#include <assert.h>
using namespace std;
bool isOutOfBounds(int row, int col, vector<vector<int>>& matrix) {
bool rowOutOfBound = row < 0 || row == matrix.size();
bool colOutOfBound = col < 0 || col == matrix[0].size();
return rowOutOfBound || colOutOfBound;
}
void explore(vector<vector<int>>& matrix, int i, int j, int prevHeight, vector<vector<bool>>& explored) {
// if we are out of bounds, or our height is greater, or if this cell was already explored
if (isOutOfBounds(i, j, matrix) || matrix[i][j] < prevHeight || explored[i][j]) return;
int height = matrix[i][j];
explored[i][j] = true;
explore(matrix, i - 1, j, height, explored); // flow up
explore(matrix, i, j + 1, height, explored); // flow right
explore(matrix, i + 1, j, height, explored); // flow down
explore(matrix, i, j - 1, height, explored); // flow left
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) {
vector<vector<int>> result;
if (matrix.size() == 0) return result;
// create boolean grids of explored paths, one for pacific, one for atlantic
vector<vector<bool>> pacific(matrix.size(), vector<bool>(matrix[0].size(), false));
vector<vector<bool>> atlantic(pacific);
for (int i = 0; i < matrix.size(); i++) {
explore(matrix, i, 0, INT_MIN, pacific); // explore first column
explore(matrix, i, matrix.size() - 1, INT_MIN, atlantic); // explore last column
}
for (int j = 0; j < matrix[0].size(); j++) {
explore(matrix, 0, j, INT_MIN, pacific); // explore first row
explore(matrix, matrix[j].size() - 1, j, INT_MIN, atlantic); // explore last row
}
// for every column of each row
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
if (pacific[i][j] && atlantic[i][j]) {
result.push_back({ i, j });
}
}
}
return result;
}
void main() {
vector<vector<int>> matrix {
{ 1, 2, 2, 3, 5 },
{ 3, 2, 3, 4, 4 },
{ 2, 4, 5, 3, 1 },
{ 6, 7, 1, 4, 5 },
{ 5, 1, 1, 2, 4 }
};
vector<vector<int>> expected{ {0, 4}, {1, 3}, {1, 4}, {2, 2}, {3, 0}, {3, 1}, {4, 0} };
vector<vector<int>> result = pacificAtlantic(matrix);
assert(result == expected);
}
I had an error when exploring last column, and last row, so was accessing invalid vector indexes.
when I fixed
for (int i = 0; i < matrix.size(); i++) {
explore(matrix, i, 0, INT_MIN, pacific); // explore first column
explore(matrix, i, matrix.size() - 1, INT_MIN, atlantic); // explore last column
}
for (int j = 0; j < matrix[0].size(); j++) {
explore(matrix, 0, j, INT_MIN, pacific); // explore first row
explore(matrix, matrix[j].size() - 1, j, INT_MIN, atlantic); // explore last row
}
the solution worked.
The code should have read as:
for (int i = 0; i < matrix.size(); i++) {
explore(matrix, i, 0, INT_MIN, pacific); // explore first column
explore(matrix, i, matrix[0].size() - 1, INT_MIN, atlantic); // explore last column
}
for (int j = 0; j < matrix[0].size(); j++) {
explore(matrix, 0, j, INT_MIN, pacific); // explore first row
explore(matrix, matrix.size() - 1, j, INT_MIN, atlantic); // explore last row
}
I have been trying to come out with a solution regarding the problem of finding the last digit of the sum of large n Fibonacci series.
I have been able to pass several test cases with large n. But I'm stuck at the following case where n = 832564823476. I know it can be solved using Pisano's period but I'm unable to come out with a efficient algo. Any help would be great. Thanks.
My code that I have implemented is as follows-
#include <iostream>
using namespace std;
int calc_fib(int n) {
int fib[n+1];
fib[0]=0;
fib[1]=1;
int res = 1;
for(int i = 2; i<=n;i++){
fib[i] = (fib[i-1]%10 + fib[i-2]%10)%10;
res = res + fib[i];
}
return (res%10);
}
int main() {
int n = 0;
std::cin >> n;
std::cout << calc_fib(n) << '\n';
return 0;
}
SOLVED IT
Works on all range of inputs. It works on the following algorithm.
The idea is to notice that the last digits of fibonacci numbers also occur in sequences of length 60 (from the previous problem: since pisano peiod of 10 is 60). Irrespective of how large n is, its last digit is going to have appeared somewhere within the sequence.
Two Things apart from edge case of 10 as last digit.
Sum of nth Fibonacci series = F(n+2) -1
Then pisano period of module 10 = let n+2 mod (60) = m then find F(m) mod(10)-1
Code as follows;
#include <iostream>
using namespace std;
long long calc_fib(long long n) {
n = (n+2)%60;
int fib[n+1];
fib[0]=0;
fib[1]=1;
int res = 1;
for(int i = 2; i<=n;i++){
fib[i] = (fib[i-1]%10 + fib[i-2]%10)%10;
// res = res + fib[i];
}
// cout<<fib[n]<<"\n";
if(fib[n] == 0){
return 9;
}
return (fib[n]%10-1);
}
int main() {
long long n = 0;
std::cin >> n;
std::cout << calc_fib(n) << '\n';
return 0;
}
Actually it's even easier than Niall answer
int get_fibonacci_sum_last_digit(long long n) {
const int kPisanoSize = 60;
int rest = n % kPisanoSize;
int preparedNumbers[kPisanoSize] = {0, 1, 2, 4, 7, 2, 0, 3, 4, 8, 3,
2, 6, 9, 6, 6, 3, 0, 4, 5, 0, 6, 7, 4, 2, 7, 0, 8, 9, 8, 8, 7,
6, 4, 1, 6, 8, 5, 4, 0, 5, 6, 2, 9, 2, 2, 5, 8, 4, 3, 8, 2, 1,
4, 6, 1, 8, 0, 9, 0};
return preparedNumbers[rest];
}
If you only need to output the last digit as you said, I think you can just make use of the Pisano Period you mentioned, as for modular 10, the cycle length is only 60 and you can just pre-make an array of that 60 digits.
If you want to compute by yourself, I think you can use Matrix Exponentiation which gives you O(lg N) complexity, when calculating the matrix exponents, keep storing the temporary result modular 10. See the Matrices section for your reference.
For your function removing the array.
#include "stdafx.h"
#include <iostream>
using namespace std;
int calc_fib(long long int n) {
int fibzero = 0;
int fibone = 1;
int fibnext;
long long int res = 1;
for (long long int i = 2; i <= n; i++) {
fibnext = (fibone + fibzero) % 10;
fibzero = fibone;
fibone = fibnext;
res = res + fibnext;
}
return (res % 10);
}
int main()
{
long long int n = 0;
std::cin >> n;
std::cout << calc_fib(n) << '\n';
return 0;
}
Last digit of Fibonacci sum repeats after 60 elements.
Here the period is 60 [0-59].
So to get the last digit of n'th sum of number is the last digit of n%60'th sum of
number
#include <iostream>
#include <vector>
#include <algorithm>
int get_last_digit(int n){
std::vector<int> last_digits(60);
long long a = 0, b = 1;
last_digits[0] = 0;
last_digits[1] = 1;
long long temp, sum = 1;
// Fill last_digits vector with the first 60 sums last digits
for (int i = 2; i < 60; i++) {
temp = a+b;
a = b;
b = temp;
sum += temp;
last_digits[i] = sum%10;
}
// Now return n%60'th element
return last_digits[n%60];
}
int main(int argc, char const *argv[]) {
int n;
std::cin>>n;
std::cout << get_last_digit(n);
return 0;
}
A neat way to solve the problem (I use java). The logic is to utilize the pisano period of 10. To write down the corresponding relationship between Sum(F(n)) = F(n+2) + 1 can help a lot. tip: create a fibonacci sequence alone.
private static long getFibonacciSum(long n) {
n = (n + 2) % 60;
long[] fib = new long[(int) n + 1];
long cor;
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++) {
fib[i] = (fib[i - 1] + fib[i - 2]) % 10;
}
if (fib[(int) n] == 0) cor = 9;
else cor = fib[(int) n] - 1;
return cor;
}
I have the adjacency matrix of a graph. I wish to calculate the number of hamiltonian paths.
I know the brute force approach tests all N! permutations. However, I am unable to code it, I tried searching but couldn't find a possible approach.
I was looking for help for the simple brute force approach.
Thanks.
See my implementation I just did:
Also check this Hamilton cycle implementation to get some insights how it's done.
#include <stdio.h>
#include <stdbool.h>
#define NUM_VERTICES 4
bool graph[NUM_VERTICES][NUM_VERTICES] = {
{0, 1, 0, 1},
{1, 0, 1, 1},
{0, 1, 0, 0},
{1, 1, 0, 0},
};
int parent[NUM_VERTICES];
bool fin_hp_r(int v, int n)
{
// If all vertices are connected
if (n == NUM_VERTICES)
return true;
// For all neighbours
for (int i = 0; i < NUM_VERTICES; ++i)
if (graph[v][i] && parent[i] == -1)
{
parent[i] = v;
if (fin_hp_r(i, n + 1))
return true;
parent[i] = -1;
}
return false;
}
bool find_hamilton_path()
{
memset(parent, -1, sizeof(int) * NUM_VERTICES);
for (int i = 0; i < NUM_VERTICES; ++i)
{
parent[i] = i;
if (fin_hp_r(i, 1))
return true;
parent[i] = -1;
}
}
int main(void) {
find_hamilton_path();
for (int i = 0; i < NUM_VERTICES; ++i)
printf ("%d -> %d\n", parent[i], i);
return 0;
}
And this one for counting number of all Hamilton paths:
#include <stdio.h>
#include <stdbool.h>
#define NUM_VERTICES 4
bool graph[NUM_VERTICES][NUM_VERTICES] = {
{0, 1, 0, 1},
{1, 0, 1, 1},
{0, 1, 0, 0},
{1, 1, 0, 0},
};
int parent[NUM_VERTICES];
long long cnt_fin_hp_r(int v, int n)
{
// If all vertices are connected
if (n == NUM_VERTICES)
return 1;
// For all neighbours
long long res = 0;
for (int i = 0; i < NUM_VERTICES; ++i)
if (graph[v][i] && parent[i] == -1)
{
parent[i] = v;
res += cnt_fin_hp_r(i, n + 1);
parent[i] = -1;
}
return res;
}
long long find_hamilton_path_number()
{
memset(parent, -1, sizeof(int) * NUM_VERTICES);
long long res = 0;
for (int i = 0; i < NUM_VERTICES; ++i)
{
parent[i] = i;
res += cnt_fin_hp_r(i, 1);
parent[i] = -1;
}
return res;
}
int main(void) {
printf("%lld\n", find_hamilton_path_number());
return 0;
}
This is a problem from an ongoing contest
https://www.codechef.com/JAN16/problems/SEAKAM
I'm trying to find path with sum of numbers is maximum. It's only allowed to move right and down through the matrix.
I've coded it but it doesn't give me the maximum sum, and I can't figure out why it does so!.
Thanks in advance.
Here's my code
/*Given grid of positive numbers, strat from (0,0) ad end at (n,n).
Move only to RIGHT and DOWN. Find path with sum of numbers is maximum. */
#include<iostream>
using namespace std;
int grid[2][3] = { { 5, 1, 2 }, { 6, 7, 8 } };
int max(int x, int y){
if (x >= y){
return x;
}
else if (x < y){
return y;
}
}
bool valid(int r, int c){
if (r + 1 == 2 || c + 1 == 3)
return false;
else
return true;
}
int maxPathSum(int row, int column){
if (!valid(row, column))
return 0;
if (row == 1 && column == 2) //base condition
return grid[row][column];
int path1 = maxPathSum(row, column + 1); //Right
int path2 = maxPathSum(row + 1, column); //Down
return grid[row][column] + max(path1, path2);
}
int main()
{
cout << maxPathSum(0, 0) << endl;
return 0;
}
the correct answer should be 26, but the output is 6.
Your function Valid should be
bool valid (int r, int c)
{
return r < 2 && c < 3;
}
and then you got 26 (Live example).
BTW, you may use dynamic programming for this problem.
You can also use dynamic programming to solve the problem
Here is the code:
#include <bits/stdc++.h>
using namespace std;
int grid[2][3] = { { 5, 1, 2 }, { 6, 7, 8 } };
int dp[3][4];
int main()
{
for(int i=0;i<4;i++)
dp[0][i] = 0;
for(int i=0;i<3;i++)
dp[i][0] = 0;
for(int i=1;i<3;i++)
{
for(int j=1;j<4;j++)
{
dp[i][j] = grid[i-1][j-1] + max(dp[i][j-1], dp[i-1][j]);
}
}
cout << dp[2][3];
return 0;
}
Live example
Apart from DP, you can also use simple (n,m) Matrix based solution. The good part is this approach wont need recursion as DP does which can cause memory issues if matrix is bigger and space complexity is just O(n x m) i.e. input array itself. And the time complexity is also O(n x m). Following code in java illustrate the approach -
package com.company.dynamicProgramming;
import static java.lang.Integer.max;
public class MaxSumPathInMatrix {
public static void main (String[] args)
{
int mat[][] = { { 10, 10, 2, 0, 20, 4 },
{ 1, 0, 0, 30, 2, 5 },
{ 200, 10, 4, 0, 2, 0 },
{ 1, 0, 2, 20, 0, 4 }
};
System.out.println(findMaxSum2(mat));
}
/*
Given a matrix of N * M. Find the maximum path sum in matrix.
Find the one path having max sum - originating from (0,0) with traversal to either right or down till (N-1, M-1)
*/
static int findMaxSum2(int mat[][])
{
int M = mat[0].length;
int N = mat.length;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
if(i==0 && j!=0){
mat[i][j]+=mat[i][j-1];
}
else if(i!=0 && j==0){
mat[i][j]+=mat[i-1][j];
}
else if (i!=0 && j!=0){
mat[i][j]+= max(mat[i-1][j], mat[i][j-1]);
}
}
}
return mat[N-1][M-1];
}
}
Run it as -
251
Process finished with exit code 0
Further Even if you are using Dynamic Programming(DP) then use Memoization concept to reduce the time complexity.. Here is the code with DP plus memoization along complexity calculation -
package com.company.dynamicProgramming;
import java.util.HashMap;
import java.util.Map;
import static java.lang.Integer.max;
public class MaxSumPathInMatrix {
static int complexity = 0;
public static void main (String[] args)
{
int mat[][] = { { 10, 10, 2, 0, 20, 4 },
{ 1, 0, 0, 30, 2, 5 },
{ 200, 10, 4, 0, 2, 0 },
{ 1, 0, 2, 20, 0, 4 }
};
System.out.println("Max Sum : " + findMaxSum2_dp(mat, 0, 0, new HashMap<>()));
System.out.println("Time complexity : " +complexity);
}
/*
~~~> solve via ~dp~ and ~memoization~
Given a matrix of N * M. Find the maximum path sum in matrix.
Find the one path having max sum - originating from (0,0) with traversal to either right or down till (m-1, n-1)
*/
static int findMaxSum2_dp(int mat[][], int i, int j, Map<String, Integer> memo){
int M = mat[0].length;
int N = mat.length;
Integer sum = memo.get(i+"-"+j);
if(sum!= null){
return sum;
}
complexity++;
if(i==N-1 && j<M-1){
mat[i][j] += findMaxSum2_dp(mat, i, j+1, memo);
memo.put(i+"-"+j, mat[i][j]);
return mat[i][j];
}
else if(i<N-1 && j==M-1){
mat[i][j] += findMaxSum2_dp(mat, i+1, j, memo);
memo.put(i+"-"+j, mat[i][j]);
return mat[i][j];
}
else if (i<N-1 && j<M-1){
int s1 = findMaxSum2_dp(mat, i+1, j, memo);
int s2 = findMaxSum2_dp(mat, i, j+1, memo);
mat[i][j] += max(s1, s2);
memo.put(i+"-"+j, mat[i][j]);
return mat[i][j];
}
return mat[N-1][M-1] += max(mat[N-1][M-2], mat[N-2][M-1]);
}
}
Two important points to note in above code -
I am storing max sum of any sub matrix [i][j] in a store(HashMap), whenever it's max sum is ready. And in further steps if this sub matrix [i][j] reappears then I take it from store instead of processing again. As a illustration - you can see [N-1][M-1] appears 2 times in below diagram of recursion -
[N][M] = max([N][M-1]) , [N-1][M]
/ \
/ \
/ \
[N][M-1] = max ([N-1][M-1], [N][M-2]) [N-1][M] = max ([N-2][M], [N-1][M-1])
Connected with Point 1 : I have provisioned a complexity variable which I increment if I have to calculate max sum for matrix [i][j] i.e. wont find in the store. If you see the result it shows 25 in 6x4 matrix i.e. the time complexity is just O(NxM).
I am trying to a C++ implementation of this knapsack problem using branch and bounding. There is a Java version on this website here: Implementing branch and bound for knapsack
I'm trying to make my C++ version print out the 90 that it should, however it's not doing that, instead, it's printing out 5.
Does anyone know where and what the problem may be?
#include <queue>
#include <iostream>
using namespace std;
struct node
{
int level;
int profit;
int weight;
int bound;
};
int bound(node u, int n, int W, vector<int> pVa, vector<int> wVa)
{
int j = 0, k = 0;
int totweight = 0;
int result = 0;
if (u.weight >= W)
{
return 0;
}
else
{
result = u.profit;
j = u.level + 1;
totweight = u.weight;
while ((j < n) && (totweight + wVa[j] <= W))
{
totweight = totweight + wVa[j];
result = result + pVa[j];
j++;
}
k = j;
if (k < n)
{
result = result + (W - totweight) * pVa[k]/wVa[k];
}
return result;
}
}
int knapsack(int n, int p[], int w[], int W)
{
queue<node> Q;
node u, v;
vector<int> pV;
vector<int> wV;
Q.empty();
for (int i = 0; i < n; i++)
{
pV.push_back(p[i]);
wV.push_back(w[i]);
}
v.level = -1;
v.profit = 0;
v.weight = 0;
int maxProfit = 0;
//v.bound = bound(v, n, W, pV, wV);
Q.push(v);
while (!Q.empty())
{
v = Q.front();
Q.pop();
if (v.level == -1)
{
u.level = 0;
}
else if (v.level != (n - 1))
{
u.level = v.level + 1;
}
u.weight = v.weight + w[u.level];
u.profit = v.profit + p[u.level];
u.bound = bound(u, n, W, pV, wV);
if (u.weight <= W && u.profit > maxProfit)
{
maxProfit = u.profit;
}
if (u.bound > maxProfit)
{
Q.push(u);
}
u.weight = v.weight;
u.profit = v.profit;
u.bound = bound(u, n, W, pV, wV);
if (u.bound > maxProfit)
{
Q.push(u);
}
}
return maxProfit;
}
int main()
{
int maxProfit;
int n = 4;
int W = 16;
int p[4] = {2, 5, 10, 5};
int w[4] = {40, 30, 50, 10};
cout << knapsack(n, p, w, W) << endl;
system("PAUSE");
}
I think you have put the profit and weight values in the wrong vectors. Change:
int p[4] = {2, 5, 10, 5};
int w[4] = {40, 30, 50, 10};
to:
int w[4] = {2, 5, 10, 5};
int p[4] = {40, 30, 50, 10};
and your program will output 90.
I believe what you are implementing is not a branch & bound algorithm exactly. It is more like an estimation based backtracking if I have to match it with something.
The problem in your algorithm is the data structure that you are using. What you are doing is to simply first push all the first levels, and then to push all second levels, and then to push all third levels to the queue and get them back in their order of insertion. You will get your result but this is simply searching the whole search space.
Instead of poping the elements with their insertion order what you need to do is to branch always on the node which has the highest estimated bound. In other words you are always branching on every node in your way regardless of their estimated bounds. Branch & bound technique gets its speed benefit from branching on only one single node each time which is most probable to lead to the result (has the highest estimated value).
Example : In your first iteration assume that you have found 2 nodes with estimated values
node1: 110
node2: 80
You are pushing them both to your queue. Your queue became "n2-n1-head" In the second iteration you are pushing two more nodes after branching on node1:
node3: 100
node4: 95
and you are adding them to you queue as well("n4-n3-n2-head". There comes the error. In the next iteration what you are going to get will be node2 but instead it should be node3 which has the highest estimated value.
So if I don't miss something in your code both your implementation and the java implementation are wrong. You should rather use a priority queue (heap) to implement a real branch & bound.
You are setting the W to 16, so the result is 5. The only item you can take into the knapsack is item 3 with profit 5 and weight 10.
#include <bits/stdc++.h>
using namespace std;
struct Item
{
float weight;
int value;
};
struct Node
{
int level, profit, bound;
float weight;
};
bool cmp(Item a, Item b)
{
double r1 = (double)a.value / a.weight;
double r2 = (double)b.value / b.weight;
return r1 > r2;
}
int bound(Node u, int n, int W, Item arr[])
{
if (u.weight >= W)
return 0;
int profit_bound = u.profit;
int j = u.level + 1;
int totweight = u.weight;
while ((j < n) && (totweight + arr[j].weight <= W))
{
totweight = totweight + arr[j].weight;
profit_bound = profit_bound + arr[j].value;
j++;
}
if (j < n)
profit_bound = profit_bound + (W - totweight) * arr[j].value /
arr[j].weight;
return profit_bound;
}
int knapsack(int W, Item arr[], int n)
{
sort(arr, arr + n, cmp);
queue<Node> Q;
Node u, v;
u.level = -1;
u.profit = u.weight = 0;
Q.push(u);
int maxProfit = 0;
while (!Q.empty())
{
u = Q.front();
Q.pop();
if (u.level == -1)
v.level = 0;
if (u.level == n-1)
continue;
v.level = u.level + 1;
v.weight = u.weight + arr[v.level].weight;
v.profit = u.profit + arr[v.level].value;
if (v.weight <= W && v.profit > maxProfit)
maxProfit = v.profit;
v.bound = bound(v, n, W, arr);
if (v.bound > maxProfit)
Q.push(v);
v.weight = u.weight;
v.profit = u.profit;
v.bound = bound(v, n, W, arr);
if (v.bound > maxProfit)
Q.push(v);
}
return maxProfit;
}
int main()
{
int W = 55; // Weight of knapsack
Item arr[] = {{10, 60}, {20, 100}, {30, 120}};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum possible profit = "
<< knapsack(W, arr, n);
return 0;
}
**SEE IF THIS HELPS**