結果

問題 No.626 Randomized 01 Knapsack
ユーザー chocoruskchocorusk
提出日時 2019-01-24 18:01:36
言語 C++11
(gcc 11.4.0)
結果
AC  
実行時間 298 ms / 2,000 ms
コード長 1,317 bytes
コンパイル時間 1,136 ms
コンパイル使用メモリ 97,212 KB
実行使用メモリ 4,352 KB
最終ジャッジ日時 2023-10-14 09:40:57
合計ジャッジ時間 5,302 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,352 KB
testcase_01 AC 2 ms
4,352 KB
testcase_02 AC 1 ms
4,352 KB
testcase_03 AC 1 ms
4,352 KB
testcase_04 AC 1 ms
4,348 KB
testcase_05 AC 2 ms
4,348 KB
testcase_06 AC 2 ms
4,348 KB
testcase_07 AC 7 ms
4,348 KB
testcase_08 AC 4 ms
4,348 KB
testcase_09 AC 21 ms
4,348 KB
testcase_10 AC 9 ms
4,348 KB
testcase_11 AC 51 ms
4,352 KB
testcase_12 AC 171 ms
4,348 KB
testcase_13 AC 113 ms
4,352 KB
testcase_14 AC 41 ms
4,348 KB
testcase_15 AC 119 ms
4,348 KB
testcase_16 AC 164 ms
4,352 KB
testcase_17 AC 143 ms
4,352 KB
testcase_18 AC 117 ms
4,348 KB
testcase_19 AC 148 ms
4,352 KB
testcase_20 AC 238 ms
4,352 KB
testcase_21 AC 152 ms
4,352 KB
testcase_22 AC 270 ms
4,348 KB
testcase_23 AC 298 ms
4,348 KB
testcase_24 AC 41 ms
4,348 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <algorithm>
#include <complex>
#include <unordered_map>
#include <unordered_set>
#include <random>
#include <cassert>
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
typedef pair<double, bool> Pd;
int n; ll W;
ll v[5001], w[5001];
int ind[5001];
ll ans;

Pd rsolve(int i, double ws, double vs){
	bool ok=1;
	for(int k=i; k<n; k++){
		double x=min((double)W-ws, (double)w[ind[k]]);
		if(x>0 && x<(double)w[ind[k]]){
			ok=0;
		}
		ws+=x;
		vs+=x/(double)w[ind[k]]*(double)v[ind[k]];
	}
	return Pd(vs, ok);
}

ll solve(int i, ll ws, ll vs){
	if(i==n){
		ans=max(vs, ans);
		return vs;
	}
	Pd p=rsolve(i, (double)ws, (double)vs);
	if(p.second) ans=max(ans, (ll)p.first);
	if(p.first<(double)ans) return 0;
	ll ret=0;
	if(ws+w[ind[i]]<=W) ret=max(ret, solve(i+1, ws+w[ind[i]], vs+v[ind[i]]));
	ret=max(ret, solve(i+1, ws, vs));
	ans=max(ret, ans);
	return ret;
}

int main()
{
	cin>>n>>W;
	for(int i=0; i<n; i++){
		ind[i]=i;
		cin>>v[i]>>w[i];
	}
	sort(ind, ind+n, [&](int i, int j){ return (double)v[i]/(double)w[i]>(double)v[j]/(double)w[j];});
	solve(0, 0, 0);
	cout<<ans<<endl;
	return 0;
}
0