# 01背包优先队列优化

## 01背包优先队列优化

struct Node {
LL w, v;
Node() {};
Node(LL _w, LL _v) {w = _w, v = _v;}
friend bool operator < (Node a, Node b) {
return a.v * b.w < b.v * a.w;
}
};


1 <= w <= 100
1 <= v <= 1e9

## AC代码：

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

typedef long long LL;

struct Node {
LL w, v;
Node() {};
Node(LL _w, LL _v) {w = _w, v = _v;}
friend bool operator < (Node a, Node b) {
return a.v * b.w < b.v * a.w;
}
};

LL dp[105];

int main()
{
LL n, m, w, v;
while(scanf("%lld%lld", &n, &m) != EOF) {
priority_queue<Node> q;
for(int i = 0; i < n; i ++) {
scanf("%lld%lld", &w, &v);
q.push(Node(w, v));
}
LL ans = 0;
while(m > 100) {
ans += q.top().v;
m -= q.top().w;
q.pop();
}
memset(dp, 0, sizeof(dp));
while(!q.empty()) {
w = q.top().w;
v = q.top().v;
q.pop();
for(int i = m; i >= w; i --) {
dp[i] = max(dp[i], dp[i - w] + v);
}
}
ans += dp[m];
printf("%lld\n", ans);
}
return 0;
}

02-21 318

05-31 197
12-14 415
08-27 304
05-18 5301
06-29 2433
04-03 242
04-26 2万+
05-27 5673