diff options
Diffstat (limited to '01-knapsack')
-rw-r--r-- | 01-knapsack/ks_dp.c | 13 |
1 files changed, 11 insertions, 2 deletions
diff --git a/01-knapsack/ks_dp.c b/01-knapsack/ks_dp.c index 6ed8d00..f40c770 100644 --- a/01-knapsack/ks_dp.c +++ b/01-knapsack/ks_dp.c @@ -37,6 +37,7 @@ typedef struct _Solver int k; // capacity int n; // items # int nw; // # bytes per bits array + int sum_w; // sum of item weight size_t sd_sz; // solver data size Item *items; // items SolverData *data; // solver data @@ -49,10 +50,12 @@ static void solve(Solver* solver) int i, j; int v, w; + int max_c, upper_bound; char *data_base; Item *item; SolverData *c, *p; + max_c = solver->sum_w; sd_sz = solver->sd_sz; nw = solver->nw; n = solver->n; @@ -68,7 +71,9 @@ static void solve(Solver* solver) c = (SolverData *) (data_base + (sd_sz * k)); p = (SolverData *) (data_base + (sd_sz * (k - w))); - for (j = k; j > 0; j--) + max_c -= w; + upper_bound = (((k - max_c) > w) ? (k - max_c) : w ); + for (j = k; j >= upper_bound; j--) { if (j < w) break; @@ -182,9 +187,13 @@ int main(int argc, char** argv, char** env) } /* read items */ + solver.sum_w = 0; item = solver.items; for (i = 0; i < solver.n; i++, item++) - fscanf(fp, "%d %d\n", &item->value, &item->weight); + { + fscanf(fp, "%d %d\n", &item->value, &item->weight); + solver.sum_w += item->weight; + } fclose(fp); if (debug) |