0/1 Knapsack problem using Dynamic Programming, Top-Down Approach [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Greeting everyone, I'm trying to solve 0/1 Knapsack problem using the Dynamic Programming Top-Down Approach. I'm pretty sure that most of my logic is correct, my code is compiling successfully. But, it's not giving the proper/correct output that is needed.
For Instance, suppose weight[] has inputs as 10,20,30 and it's corresponding value[] has 60,100,120. The max weight that the Knapsack can hold onto is 50. The max profit should be 220, but my code is giving me the answer 280 instead. Please help me, here's my piece of code:-
#include<bits/stdc++.h>
using namespace std;
void knapsack(vector<int>& weight, vector<int>& value, int w, int n){
vector<vector<int>> t;
for(int i=0;i<n+1;++i){
vector<int> temp;
for(int j=0;j<w+1;++j){
int x =0;
temp.push_back(x);
}
t.push_back(temp);
temp.clear();
}
for(int i=1;i<n+1;++i){
for(int j=1;j<w+1;++j){
if(weight[i-1]<=w){
t[i][j] = max(value[i-1]+t[i-1][w-weight[i-1]], t[i-1][j]);
}
else{
t[i][j] = t[i-1][j];
}
}
}
cout<<"Max Profit: "<<t[n][w];
// return final;
// vector<int> oneDimVector;
// for(int i = 0; i < n+1; i++){
// for(int j = 0; j < w+1; j++){
// oneDimVector.push_back(t[i][j]);
// }
// }
// vector<int>::iterator maxElement;
// maxElement = max_element(oneDimVector.begin(), oneDimVector.end());
// cout<<"Max Profit: "<<*maxElement;
}
int main(){
int n;
int w;//Total weight of knapsack
cin>>n;
cin>>w;
vector<int> weight;
vector<int> value;
for(int i=0;i<n;++i){
int x;
cin>>x;
weight.push_back(x);
}
for(int i=0;i<n;++i){
int x;
cin>>x;
value.push_back(x);
}
knapsack(weight,value,w,n);
}

I again debugged my code, I had to change one variable which I had written wrong in the following line of code:-
t[i][j] = max(value[i-1]+t[i-1][w-weight[i-1]], t[i-1][j]);
here, it should be:-
t[i][j] = max(value[i-1] + t[i-1][ j - weight[i-1]], t[i-1][j]);

Related

Maximum sum subarray, C++, DSA [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I had tried to write a program to find the maximum sum subarray, I am able to take the output correctly in a certain scenario but if I want to change it the output is not as desired. So anyone can help me?
#include<iostream>
using namespace std;
int main(){
int minValue,n;
int a[n]={4,-2,-3,4,-1,-2,1,5,-3};
int max_so_far = minValue;
int max_ending_here=0;
int start=0, end=0, s=0;
for(int i=0; i<n;i++){
max_ending_here = max_ending_here+a[i];
if(max_so_far < max_ending_here){
max_so_far = max_ending_here;
start=s;
end = i;
}
if(max_ending_here<0){
max_ending_here=0;
s = i+1;
}
start=s;
}
cout<<"maximum sum subarray is: "<<max_so_far;
cout<<"\nstart "<<start;
//cout<<"\nend "<<end;
return 0;
}
The output of this code is:
maximum sum subarray is: 7
start 3
But if I try to print the value of end as well as shown in the following program:
#include<iostream>
using namespace std;
int main()
{
int minValue,n;
int a[n]={4,-2,-3,4,-1,-2,1,5,-3};
int max_so_far = minValue;
int max_ending_here=0;
int start=0, end=0, s=0;
for(int i=0; i<n;i++)
{
max_ending_here = max_ending_here+a[i];
if(max_so_far < max_ending_here){
max_so_far = max_ending_here;
start=s;
end = i;
}
if(max_ending_here<0){
max_ending_here=0;
s = i+1;
}
start=s;
}
cout<<"maximum sum subarray is: "<<max_so_far;
cout<<"\nstart "<<start;
cout<<"\nend "<<end;
return 0;
}
The output becomes as:
maximum sum subarray is: 32760
start 3
end 0
Can anybody point out the actual error for me?
Here I made 2 changes:
Used INT_MIN
Used vector instead of array definition.
#include<iostream>
using namespace std;
int main()
{
vector<int> a ={4,-2,-3,4,-1,-2,1,5,-3}; // <------------ here
int minValue=INT_MIN, n= a.size(); // <--------- here
int max_so_far = minValue;
int max_ending_here=0;
int start=0, end=0, s=0;
for(int i=0; i<n;i++)
{
max_ending_here = max_ending_here+a[i];
if(max_so_far < max_ending_here){
max_so_far = max_ending_here;
start=s;
end = i;
}
if(max_ending_here<0){
max_ending_here=0;
s = i+1;
}
start=s;
}
cout<<"maximum sum subarray is: "<<max_so_far;
cout<<"\nstart "<<start;
cout<<"\nend "<<end;
return 0;
}
OUTPUT:
maximum sum subarray is: 7
start 3
end 7

Vector not defined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have added bits/stdc+.h and vector both.
Still this error is coming .
Can anyone tell me why this is happening.
#include <bits/stdc++.h>
#include<vector>
void rotate(int arr[], int n);
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int a[n] , i;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
rotate(a, n);
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
return 0;
}
// } Driver Code Ends
//User function Template for C++
void rotate(int arr[], int n)
{
vector<int> a;
a[0] = arr[n-1];
for(int i = 0 ; i<n-1 ;i++)
{
a.insert(a.back(), arr[i]);
}
for(int j : a)
cout<<j;
}
main.cpp:30:5: error: ‘vector’ was not declared in this scope
vector<int> a;
^~~~~~
Follow these: (EDITED)
(SOLUTION TO YOUR PROBLEM) Use, using namespace std as it means if the compiler finds something that is not declared in the current scope then it will go and check std.
Don't mix c and c++ syntax. Either use printf or cout.
Also check the 1st comment on this answer, as there is something you should know about "using namespace std" and "cout/cin".
No need to work two times, you can also declare and define your function at once.
Solution (but have an error in other parts)
#include <bits/stdc++.h>
using namespace std;
void rotate(int arr[], int n)
{
vector<int> a;
a[0] = arr[n - 1];
for (int i = 0 ; i < n - 1 ; i++)
{
a.insert(a.back(), arr[i]); // ITS YOUR SYNTAX, CONSIDER TO UPDATE IT
}
for (auto &it : a)
cout << it;
}
int main()
{
int t;
cin>>t;
while (t--)
{
int n;
cin>>t;
int a[n] , i;
for (i = 0; i < n; i++)
cin>>a[i];
rotate(a, n);
for (i = 0; i < n; i++)
cout<<a[i];
cout<<"\n";
}
return 0;
}
CHECK LINE NO 9 line,
and see if it's correct or not.
a.insert(a.back(), arr[i]); WRONG
You are doing something wrong there. Check this statement
error: ‘vector’ was not declared in this scope
Solved by using namespace
If you liked this answer. Please consider ticking this answer.:)

Why I'm getting WA(Wrong Answer) in CMPRSS problem of codechef? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm getting WA(Wrong Answer) in "Compress the List" problem Code(CMPRSS) of CodeChef, here is the link of the problem: https://www.codechef.com/problems/CMPRSS
I've checked the sample output given in the problem and also some self made test cases and It's working properly.I'm not getting what's wrong in my code
here is my approach:
#include <bits/stdc++.h>
using namespace std;
vector<int> number;
int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
for(int i=0;i<n;i++){
int temp;
cin>>temp;
number.push_back(temp);
}
int i;
for(i=0;i<n-1;i++){
int count = 0;
int temp = i;
while (number[temp+1]-number[temp]==1){
temp++;
count++;
}
if(count>1){
if(i+count==n-1){
cout<<number[i]<<"..."<<number[i+count]<<"\n";
} else{
cout<<number[i]<<"..."<<number[i+count]<<",";
}
i = i + count;
}
else{
cout<<number[i]<<",";
}
}
if(i!=n){
cout<<number[n-1]<<"\n";
}
number.clear();
}
return 0;
}
You forgot to check if number[temp+1] exists in the part
while (number[temp+1]-number[temp]==1){
temp++;
count++;
}
Therefore, it may read beyond the array and produce wrong output.
Try this case:
2
5
1 2 3 4 5
3
1 2 3
The part should be like this:
while (temp+1 < static_cast<int>(number.size()) && number[temp+1]-number[temp]==1){
temp++;
count++;
}
Your logic is partially correct because you forgot to check the upper limit index of vector: Please check the missing code in the bold letter or between ** code **:
#include <bits/stdc++.h>
using namespace std;
vector number;
int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
for(int i=0;i<n;i++){
int temp;
cin>>temp;
number.push_back(temp);
}
int i;
for(i=0;i<n-1;i++){
int count = 0;
int temp = i;
while (**temp+1<n &&** number[temp+1]-number[temp]==1){
temp++;
count++;
}
if(count>1){
if(i+count==n-1){
cout<<number[i]<<"..."<<number[i+count]<<"\n";
} else{
cout<<number[i]<<"..."<<number[i+count]<<",";
}
i = i + count;
}
else{
cout<<number[i]<<",";
}
}
if(i!=n){
cout<<number[n-1]<<"\n";
}
number.clear();
}
return 0;
}
Check my solution.

Skipped condition and I don't know why [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I was debugging this, and debugger skipped the last 'if' even 'sum' was equal to 'n' and jump straight to 'else', I don't know why. Please help.
P/s: Can I use dynamic array to increase the mobility of my program?
#include <iostream>
#include <math.h>
using namespace std;
int exponent_of_10(); // set position for digits
int exponent_of_10(int a, int b){
for(int j = b; j>0;j--)
{
a *= 10;
}
return a;
}
main() //check if the number was palindromic
{
int n;
int a[6]={0,0,0,0,0,0};
int i = 0;
int temp;
int S;
cout<< "Input n (maximum of 6 digits): ";
cin>> n;
do
{
if(n<1)
{break;}
temp=n%10;
a[i]=temp;
n=(n-temp)/10;
i++;
}
while (n!=0);
int sum = 0;
for(int j=0; j<=5; j++)
{
exponent_of_10(a[j],j);
S = exponent_of_10(a[j],j);
if (S==0)
{break;}
sum +=S;
}
if(sum==n)
{
cout<< "Congratz, this is PALIDROMIC NUMBER !!";
}
else
cout<< "Sad life, this is NOT palidromic number";
return 0;
}
When the code exits the do ... while() loop, n is 0. For the test in the if to be meaningful, the code should save the original value of n somewhere and compare sum to that original value.

issues with Storing to array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was testing one of my classes, but for some reason I can't seem to cast an intiger from a 2d array to double. Here is my (very simplified) code:
In main.cpp
#include<iostream>
#include<conio.h>
#include<string>
#include "trajectories.h"
int main()
{
std::string response;
int numOfCoords;
int speed;
int ** coords;
std::cout<<"enter the number of coordinates: ";
std::cin>>numOfCoords;
std::cout<<"enter speed: ";
std::cin>>speed;
coords=new int *[numOfCoords];
for (int i=0; i<numOfCoords; i++)
coords[i] = new int[2];
for(int i=0; i<numOfCoords*2; i++)
{
if(i%2==0)
std::cout<<"enter point "<<i/2<<".x : ";
else
std::cout<<"enter point "<<i/2<<".y : ";
std::cin>>coords[i/2][i%2];
}
NPCTrajectory traj(numOfCoords, speed);
traj.AddCoordinates(coords);
std::cout<<coords[0][0]<<", "<<coords[0][1]<<std::endl;
getch();
double currentCoords[2];
currentCoords[0]=double(coords[0][0]);
currentCoords[1]=double(coords[0][1]);
for(;;)
{
traj.HandleEvents(currentCoords);
std::cout<<"current coordinates : ("<<currentCoords[0]<<", "<<currentCoords[1]<<")"<<std::endl;
std::cout<<"do you wish to continue? ";
getch();
}
}
Trajectories.h contains class declaration only, so I believe it is irrelevant. Here is my trajectories.cpp
#include "trajectories.h"
int FPSCap=5;
NPCTrajectory::NPCTrajectory(int npoints, int newSpeed)
{
numOfPoints=npoints;
this->speed=newSpeed;
points = new int * [npoints];
for (int i=0; i<npoints; i++)
points[npoints] = new int[2];
state = 0;
maxOffset=speed/FPSCap;
}
void NPCTrajectory::AddCoordinates(int ** coordinates)
{
for(int i=0;i<this->numOfPoints; i++)
{
points[i][0]=coordinates[i][0];
points[i][1]=coordinates[i][1];
}
}
void NPCTrajectory::HandleEvents(double (&currentCoordinates)[2])
{
if(state+1==numOfPoints) return;
if(Distance(currentCoordinates[0], currentCoordinates[1], (double)points[state+1][0], (double)points[state+1][1])<maxOffset) state++;
double ratio = maxOffset/Distance(currentCoordinates[0], currentCoordinates[1], (double)points[state+1][0], (double)points[state+1][1]);
currentCoordinates[0]+=(points[state+1][0]-currentCoordinates[0])*ratio;
currentCoordinates[1]+=(points[state+1][1]-currentCoordinates[1])*ratio;
}
Please note that removing command traj.AddCoordinates(coords) will make the problem disappear. Am I passing the array correctly to the function?
The problem is in your constructor NPCTrajectory. Replace npoints with loop variable i. The following code:
for (int i=0; i<npoints; i++)
points[npoints] = new int[2];
should be like:
for (int i=0; i<npoints; i++)
points[i] = new int[2];
Because of this incorrect allocation, you are getting error (segmentation fault) in AddCoordinates function when you try to access points[i][0] with i=0 (assuming you are giving npoints>0 in NPCTrajectory).