結果

問題 No.3670 Fast Knapsack
コンテスト
ユーザー t98slider
提出日時 2026-09-05 12:47:45
言語 C++23
(gcc 15.3.0 + boost 1.92.0 + ACL)
コンパイル:
g++-15 -O2 -lm -std=c++23 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
TLE  
実行時間 -
コード長 1,929 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 3,041 ms
コンパイル使用メモリ 364,152 KB
実行使用メモリ 6,272 KB
最終ジャッジ日時 2026-09-05 12:48:02
合計ジャッジ時間 7,795 ms
ジャッジサーバーID
(参考情報)
judge3_0 / judge4_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 1 TLE * 1 -- * 23
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;

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

constexpr int MAXLEN = 1 << 18;
template<int len> int solve(int N, int S, vector<int> &a) {
    if (len <= S) return solve<min(len * 2, MAXLEN)>(N, S, a);

    bitset<len> dp;
    dp[0] = 1;

    int i = 0;
    for(i = 0; i < N && 2 * a[i] <= S;) {
        int p = i;
        while(i < N && a[i] == a[p]) i++;
        int cnt = i - p;
        for(int take = 1; cnt > 0; take *= 2) {
            int D = min(take, cnt);
            long long shift = (ll)(a[p]) * D;
            cnt -= D;
            if(shift <= S) dp |= dp << shift;
        }
    }
    int j = S;
    if(dp[S]) return S;
    int ans = 0;
    while(i < N){
        while(a[i] + j > S) j--;
        while(j >= 0 && !dp[j]) j--;
        if(j < 0) return ans;
        ans = max(ans, j + a[i]);
    }
    return ans;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int T;
    cin >> T;
    while(T--) {
        int N, S, g = 0;
        cin >> N >> S;
        vector<int> a(N);
        ll tot = 0;
        for(auto &&v : a) cin >> v, tot += v;
        
        if(tot <= S){
            cout << tot << '\n';
            continue;
        }

        sort(a.begin(), a.end());
        while(!a.empty() && a.back() > S) a.pop_back();
        N = a.size();

        if(N <= 12){
            int ans = 0;
            for(int i = 1; i < (1 << N); i++){
                int sv = 0;
                for(int j = 0; j < N; j++){
                    if(i >> j & 1) sv += a[j];
                }
                if(sv <= S) ans = max(ans, sv);
            }
            cout << ans << '\n';
            continue;
        }

        for(auto &&v : a) g = gcd(g, v);

        if(g >= 2){
            S /= g;
            for(auto &&v : a) v /= g;
        }

        cout << g * solve<16>(N, S, a) << '\n';
    }
}
0