結果

問題 No.10 +か×か
ユーザー stqnstqn
提出日時 2014-12-09 19:53:42
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 3,155 ms / 5,000 ms
コード長 1,803 bytes
コンパイル時間 1,354 ms
コンパイル使用メモリ 146,804 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-08-21 06:09:12
合計ジャッジ時間 5,115 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,376 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 51 ms
4,376 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 2 ms
4,380 KB
testcase_06 AC 20 ms
4,380 KB
testcase_07 AC 3,155 ms
4,380 KB
testcase_08 AC 2 ms
4,380 KB
testcase_09 AC 2 ms
4,376 KB
testcase_10 AC 2 ms
4,380 KB
testcase_11 AC 2 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

#define rep(i,n) repi(i,0,n)
#define repi(i,a,b) for(int i=int(a);i<int(b);++i)
#define long int64_t
#define ulong uint64_t

const int N = 50;
int n, total, a[N];

void input()
{
    cin >> n >> total;
    rep(i, n) cin >> a[i];
}

const int inf = 1000000;

int min_a[N], max_c[N], max_d[N];

inline int min_result(int i, int cur) { return cur + min_a[i]; }
inline int max_result(int i, int cur) { return min<long>((long) max_c[i] * cur + max_d[i], inf); }

void prepare()
{
    min_a[n - 1] = a[n - 1] == 1 ? 0 : a[n - 1];
    max_c[n - 1] = a[n - 1] == 1 ? 1 : a[n - 1];
    max_d[n - 1] = a[n - 1] == 1 ? 1 : 0;
    for (int i = n - 2; i >= 0; --i) {
        min_a[i] = a[i] == 1 ? min_a[i + 1] : min_a[i + 1] + a[i];
        max_c[i] = a[i] == 1 ? max_c[i + 1] : min<long>((long) max_c[i + 1] * a[i], inf);
        max_d[i] = a[i] == 1 ? max_d[i + 1] + max_c[i + 1] : max_d[i + 1];
    }
}

bool dfs(int i, int cur)
{
    if (i == n) return cur == total;
    if (total < min_result(i, cur) or max_result(i, cur) < total) return false;
    return dfs(i + 1, cur + a[i]) or dfs(i + 1, cur * a[i]);
}

void solve()
{
    string tmp;
    while (n and total % a[n - 1] != 0) {
        tmp.push_back('+');
        total -= a[--n];
    }
    reverse(tmp.begin(), tmp.end());

    prepare();

    string ans;
    int cur = a[0];
    repi(i, 1, n) {
        if (dfs(i + 1, cur + a[i])) {
            ans.push_back('+'), cur += a[i];
        } else {
            ans.push_back('*'), cur *= a[i];
        }
    }
    ans.insert(ans.end(), tmp.begin(), tmp.end());
    cout << ans << endl;
}

int main()
{
    cin.tie(0);
    ios_base::sync_with_stdio(false);

    input();
    solve();
}
0