-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsack problem.cpp
More file actions
56 lines (45 loc) · 942 Bytes
/
Knapsack problem.cpp
File metadata and controls
56 lines (45 loc) · 942 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<stdlib.h>
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
unsigned long int n, w;
vector<unsigned long int> numbers;
bool sol[40];
bool solution_found = false;
int sum(int index){
int res = 0;
for(int i = index; i < n; i++)
res += numbers[i];
return res;
}
bool Compute(int index, int s){
if(s == w)
return true;
if(index != n)
for(int i = 1; i >= 0; i--){
sol[index] = i;
int k = s + (sol[index]? numbers[index]: 0);
if(k <= w && sum(index) + s >= w)
if(Compute(index + 1, k))
return true;
}
return false;
}
int main(){
FILE *In = fopen("input.txt", "r");
FILE *Out = fopen("output.txt", "w");
fscanf(In,"%d %d", &n, &w);
for(int i = 0; i < n; i++){
int x;
fscanf(In, "%d", &x);
numbers.push_back(x);
}
fclose(In);
if(Compute(0, 0))
for(int i = 0; i < n; i++)
fprintf(Out, "%d ", sol[i]? 1: 0);
else
fprintf(Out, "%d", -1);
fclose(Out);
}