'I run into a segmentation fault with one of the test cases. The test cases are hidden
The image below is the problem with sample input and output. enter image description here
I run into a segmentation fault with one of the test cases. The test cases are hidden. 5 out of 6 test cases work but for one of the test cases I get a segmentation fault.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
//utility function to return maximum of two integers
int max(int x, int y) {
return (x > y) ? x : y;
}
//function to return maximum profit
int fractionalKnapsack(int capacity, int weight[], int vec[], int num) {
int wt, i;
int K[num+1][capacity+1];
//iterate nested loop
for (i = 0; i <= num; i++) {
for (wt = 0; wt <= capacity; wt++) {
//base case
if (i == 0 || wt == 0)
K[i][wt] = 0;
//otherwise if
else if (weight[i - 1] <= wt)
K[i][wt] = max(vec[i - 1] + K[i - 1][wt - weight[i - 1]], K[i - 1][wt]);
//otherwise
else
K[i][wt] = K[i - 1][wt];
}
}
return K[num][capacity];
}
//driver code
int main() {
int capacity,num;
//input knapsac capacity and number of objects
cin >> capacity>>num;
int vec[num], weight[num];
//input weight and value
for (int i = 0; i < num; i++) {
cin >> weight[i]>>vec[i];
}
//print result
cout<< fractionalKnapsack(capacity, weight, vec, num)<<endl;
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
