kiwirafe.blog

Minimum Total Sum - Optimal Selection

While reading Competitive Programmer’s Handbook, I have encountered a problem that combines Dynamic Programming and Bit Masking.

Example:

Consider the following table:

Days 0 1 2 3 4 5 6 7
Product 1 6 9 5 2 8 9 1 6
Product 2 8 2 6 2 7 5 7 2
Product 3 5 3 9 7 3 5 1 4

The input would be as follows:

Input:
3 8
6 9 5 2 8 9 1 6
8 2 6 2 7 5 7 2
5 3 9 7 3 5 1 4
Output:
5

Sample C++ Code

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n, k;
    cin >> k >> n;
    int price[k][n];
    int total[1 << k][n];

    for (int i = 0; i < k; i++)
        for (int j = 0; j < n; j++)
            cin >> price[i][j];

    for (int s = 0; s < (1 << k); s++)
        for (int x = 0; x < k; x++)
            if (s & (1 << x))
                total[s][0] = price[x][0];

    for (int d = 1; d < n; d++) {
        for (int s = 0; s < (1 << k); s++) {
            total[s][d] = total[s][d - 1];
            for (int x = 0; x < k; x++) {
                if (s & (1 << x)) {
                    total[s][d] = min(total[s][d], total[s ^ (1 << x)][d - 1] + price[x][d]);
                    break;
                }
            }
        }
    }

    cout << total[(1 << k) - 1][n - 1] << endl;
}