P1048 题解
本题正解为 01 背包,本题解并非传统意义上的正解。如果想学习正解,请参考其它题解。
第一次看到这道题时可能会有一种想法:按性价比排序后贪心选取。
但是这样是错误的,反例:
60 3
2 30
29 30
30 31
(贪心的答案为
不正确不代表这个思路没有用,我们考虑对其进行改进。容易发现,虽然性价比的大小不能确定这个物品选还是不选,但是显然性价比更大的物品更容易被选到。所以我们还是对物品先按照性价比排一下序。
所以我们考虑给一个物品赋上一个权值
我们可以考虑这样赋权值:先设定一个数
可以一边赋权值一边计算答案,对于重量大于当前所剩容量的物品可以直接跳过。
当然,因为这种算法实在是太随机了,一次可能找不到最优解,所以需要多次查找最优解,我们可以一直枚举到
多次提交发现,当
当然,这只是数据比较随机的情况,对于出题人故意卡贪心的数据,可能需要通过调整
代码如下:
#include <bits/stdc++.h>
using namespace std;
#define MAXN 101
mt19937 rnd(time(0));
int n, W, ans;
struct Node{
int v, w;
}a[MAXN];
bool cmp(Node a, Node b){
return double(a.v)*double(b.w) > double(b.v)*double(a.w);
}
bool get(int x){
return rnd() % 100 < x;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> W >> n;
for (int i(1); i<=n; ++i){
cin >> a[i].w >> a[i].v;
if (a[i].w > W){
--i;
--n;
}
}
sort(a+1, a+n+1, cmp);
while (double(clock()) / CLOCKS_PER_SEC < 0.004){
int tmp(W), res(0), g(97);
for (int i(1); i<=n; ++i){
if (a[i].w > tmp) continue;
if (get(g)){
tmp -= a[i].w;
res += a[i].v;
}
g -= get(20);
}
ans = max(ans, res);
}
cout << ans;
return 0;
}