[C ++] 01 knapsack problem

1. The basic problem

There are N items V and a capacity of the backpack. Into the first \ (I \) items consumed space \ (C_i \) , the resulting value is \ (W_i \) . Solving the items into a backpack which allows the maximum value of the sum.

1.1 ideas

This is the most basic knapsack problem, characterized by: each item is only one, you can select or leave out. Subproblem defined by the state: i.e. \ (F [i, v] \) indicates just before the i items placed in a maximum capacity value v backpack available. It is the state transition equation:
\ (F. [I, V] = max \ {F. [. 1-I, V], F. [. 1-I, V-C_i] + W_i \} \)

1.2 core code

memset(F[0], 0, sizeof(F[0]));
for (int i = 1; i <= n; ++i) {
    for (int v = 0; v <= V; ++v) {
        if (v >= c[i]) F[i][v] = max(F[i-1][v], F[i-1][v-c[i]] + w[i]);
        else F[i][v] = F[i-1][v];
    }
}
for (int i = 0; i <= V; ++i) ans = max(ans, F[n][i]);

Time complexity and space complexity are \ (O (NV) \) , wherein the time complexity can not be substantially optimized, but the spatial complexity, but can be optimized to \ (O (V) \) .

memset(F, 0, sizeof(F));
for (int i = 1; i <= n; ++i) {
    for (int v = V; v >= c[i]; --v) {
        F[v] = max(F[v], F[v-c[i]] + w[i]);
    }
}
for (int i = 0; i <= V; ++i) ans = max(ans, F[i]);

2. The number of programs seeking

Look a question: small A la carte
question is asked for such changes, the general simply state transition equation \ (max \) into \ (sum \) can be. For example, if each item are completely backpack article transfer equation is the
\ (F [i, v] = sum \ {F [i-1, v], F [i, v-C_i] \} \)

The initial condition is \ (F. [0,0] =. 1 \) .

F[0][0] = 1;
for (int i = 1; i <= n; ++i) {
    for (int v = 0; v <= V; ++v) {
        if (v >= c[i]) F[i][v] = F[i-1][v] + F[i-1][v-c[i]];
        else F[i][v] = F[i-1][v];
    }
}
ans = F[n][V];
printf("%d\n", ans); 

3. Try to pretend to seek full

Look a question: packing problem [NOIp2001 universal set of question 4]
In fact, here \ (W_i \) is \ (C_i \) .

memset(F, 0, sizeof(F));
for (int i = 1; i <= n; ++i) {
    for (int v = V; v >= c[i]; --v) {
        F[v] = max(F[v], F[v-c[i]] + c[i]);
    }
}
for (int i = 0; i <= V; ++i) ans = max(ans, F[i]);
printf("%d\n", V - ans);

4. The volume of all possible seek

Came a question: building castle
calculated the number of each castle heights.

for (int i = 0; i < n; ++i) {
    int np = 0;
    int now;
    int sum = 0;
    while (1) {
        scanf("%d", &now);
        if (now == -1) break;
        a[++np] = now;
        sum += now;
    }
    if (max_sum < sum) max_sum = sum;
    memset(F, 0, sizeof(F));
    F[0] = 1;
    for (int j = 1; j <= np; ++j) {
        for (int v = sum; v >= a[j]; --v) {
            if (F[v-a[j]] && !F[v]) {
                ++h[v];
                F[v] = 1;
            }
        }
    }
}

Guess you like

Origin www.cnblogs.com/szdytom/p/12203393.html