-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubsum.c
52 lines (44 loc) · 779 Bytes
/
subsum.c
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
#include <stdio.h>
int max(int a, int b)
{
if (a > b)
return a;
else
return b;
}
void printmatrix(int n, int V, int M[n][V])
{
for (int i = 0; i < n; i++)
{
printf("%d ", i);
for (int j = 0; j < V; j++)
printf("%d ", M[i][j]);
printf("\n");
}
}
int subsum(int w[], int n, int W, int M[n][W])
{
for (int j = 0; j < W; j++)
M[0][j] = 0;
for (int i = 1; i < n; i++)
{
for (int j = 0; j < W; j++)
{
if (w[i] > j)
M[i][j] = M[i-1][j];
else
M[i][j] = max(M[i-1][j], w[i]+M[i-1][j-w[i]]);
}
}
printmatrix(n, W, M);
return M[n-1][W-1];
}
int main()
{
int w[] = {0, 2, 2, 3};
int n = sizeof(w)/sizeof(w[0]);
int W = 7;
int M[n][W];
printf("\nLa soluzione ottima ha somma %d\n", subsum(w, n, W, M));
return 0;
}