結果
問題 | No.626 Randomized 01 Knapsack |
ユーザー |
|
提出日時 | 2017-12-18 09:25:13 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
WA
|
実行時間 | - |
コード長 | 2,753 bytes |
コンパイル時間 | 1,440 ms |
コンパイル使用メモリ | 100,000 KB |
最終ジャッジ日時 | 2025-01-05 05:53:07 |
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 2 WA * 23 |
ソースコード
#include <iostream>#include <vector>#include <algorithm>#include <numeric>#include <functional>#define repeat(i,n) for (int i = 0; (i) < (n); ++(i))#define repeat_reverse(i,n) for (int i = (n)-1; (i) >= 0; --(i))typedef long long ll;template <typename T> bool setmax(T & l, T const & r) { if (not (l < r)) return false; l = r; return true; }template <typename T> bool setmin(T & l, T const & r) { if (not (r < l)) return false; l = r; return true; }using namespace std;int main() {int n; ll lim_w; cin >> n >> lim_w;vector<ll> v(n), w(n); repeat (i,n) cin >> v[i] >> w[i];ll max_v = *max_element(v.begin(), v.end());ll max_w = *max_element(w.begin(), w.end());ll sum_w = accumulate(w.begin(), w.end(), 0ll);ll sum_v = accumulate(v.begin(), v.end(), 0ll);ll ans = 0;if (sum_w <= lim_w) {ans = sum_v;} else if (n <= 30) { // branch and bound/* sort by the efficiency */ {vector<int> xs(n); repeat (i,n) xs[i] = i;sort(xs.begin(), xs.end(), [&](int i, int j) -> bool { return v[i] * w[j] > v[j] * w[i]; });vector<ll> tv = v, tw = w;repeat (i,n) { v[i] = tv[xs[i]]; w[i] = tw[xs[i]]; }}function<void (int, ll, ll)> f = [&](int i, ll cur_v, ll cur_w) {if (lim_w < cur_w) return; // not executableif (i == n) { setmax(ans, cur_v); return; } // terminatell lr_v = cur_v; // linear relaxationll lr_w = cur_w;int j;for (j = i; j < n and lr_w + w[j] <= lim_w; ++ j) { // greedylr_w += w[j];lr_v += v[j];}if (lr_w == lim_w or j == n) { setmax(ans, lr_v); return; } // accept greedydouble lr_ans = lr_v + v[j] * ((lim_w - lr_w) /(double) w[j]);if (lr_ans <= ans) return; // boundf(i+1, cur_v+v[i], cur_w+w[i]);f(i+1, cur_v, cur_w );};f(0, 0, 0);} else if (max_w <= 1000) { // dynamic programmingvector<ll> dp(lim_w+1);repeat (i,n) {repeat_reverse (j, lim_w-w[i]+1) {setmax(dp[j + w[i]], dp[j] + v[i]);}}repeat (j, lim_w+1) {setmax(ans, dp[j]);}} else if (max_v <= 1000) { // dynamic programmingvector<ll> dp(sum_v+1, lim_w+1);dp[0] = 0;repeat (i,n) {repeat_reverse (j, sum_v-v[i]+1) {setmin(dp[j + v[i]], dp[j] + w[i]);}}repeat_reverse (j, sum_v+1) {if (dp[j] <= lim_w) {ans = j;break;}}}cout << ans << endl;return 0;}