-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGreedy_algorithm_Knapsack.cpp
More file actions
55 lines (52 loc) · 1013 Bytes
/
Copy pathGreedy_algorithm_Knapsack.cpp
File metadata and controls
55 lines (52 loc) · 1013 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
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
#define s scanf
#define p printf
typedef struct
{
int value,weight;
}str;
str arr[100];
int main()
{
int mat[101][101];
int a,b,c,i,j,max_w,item;
while(s("%d",&item)==1)
{
for(i=1;i<=item;++i)
s("%d %d",&arr[i].value,&arr[i].weight);
memset(mat,0,sizeof(mat));
s("%d",&max_w);
for(i=1;i<=item;++i)
{
for(j=1;j<=max_w;++j)
{
a=mat[i-1][j];
c=j-arr[i].weight;
if(c>-1)
b=mat[i-1][c]+arr[i].value;
else
b=0;
if(a>b)
mat[i][j]=a;
else
mat[i][j]=b;
}
}
p("Maximum profit is: %d\n\n",mat[item][max_w]);
}
return 0;
}
/*
Input:
4
10 5
40 4
30 6
50 3
10
Output:
Maximum profit is: 90
*/