summaryrefslogtreecommitdiffstats
path: root/01-knapsack/0-works-only-if-sorted-by-val-or-weight-asc.patch
blob: bb4a6e18ed784051e73a0433deaf0c646a9324de (plain)
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
diff --git a/01-knapsack/ks_dp-ng.c b/01-knapsack/ks_dp-ng.c
index 7830651..106328b 100644
--- a/01-knapsack/ks_dp-ng.c
+++ b/01-knapsack/ks_dp-ng.c
@@ -120,20 +120,32 @@ static void solve(Solver* solver)
 
         // this computes the top-left bottom-right diagonal,
         // values above this don't need to be computed
+        j = k;
         min_c -= w;
         lower_bound = (k - min_c);
         if (lower_bound < w)
           lower_bound = w;
-        for (j = k; j >= lower_bound; j--, data--, up_left--)
+
+        while (j >= lower_bound)
           {
              counter++;
+               /* printf("  % 4d\n", j); */
 
              if (data->v < (v + up_left->v))
                {
                   data->i = i;
                   data->v = v + up_left->v;
                   data->w = w + up_left->w;
+                  if (j == k) {
+                       j -= w;
+                       data -= w;
+                       up_left -= w;
+                       continue;
+                  }
                }
+             j--;
+             data--;
+             up_left--;
           }
 
         if (debug > 2)