yukicoder No.10 - +か×か

解法

(i番目以降の項でtotal-jを作れるか)でbool DPします. 経路復元するときは, (0, 0)からなるべく+を選ぶように状態を進めていけば, 辞書順最小になります.

ソースコード

#include <iostream>
#include <cstring>
using namespace std;

const int MAX_N = 60;
const int MAX_TOTAL = 100010;

int a[MAX_N];

bool dp[MAX_N][MAX_TOTAL];

int main() {
    int n, total;
    cin >> n >> total;

    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }

    memset(dp, false, sizeof(dp));

    dp[n][total] = true;
    for (int i = n - 1; i >= 0; i--) {
        for (int tot = 0; tot <= total; tot++) {
            if (tot + a[i] <= total) {
                dp[i][tot] |= dp[i + 1][tot + a[i]];
            }
            if (tot * a[i] <= total) {
                dp[i][tot] |= dp[i + 1][tot * a[i]];
            }
        }
    }

    int idx = 1,
        cur_total = a[0];
    while (idx < n) {
        if (dp[idx + 1][cur_total + a[idx]]) {
            cout << "+";
            cur_total += a[idx];
        } else {
            cout << "*";
            cur_total *= a[idx];
        }
        idx++;
    }
    cout << endl;

    return 0;
}

感想

星4の問題にしては簡単でした. 試験勉強しないと…(絶望)