Pagini recente » Cod sursa (job #813136) | Cod sursa (job #2728707) | Cod sursa (job #2557357) | Cod sursa (job #3146413) | Cod sursa (job #3254916)
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int nmax = 5000, mod = 1e9 + 7, inf = 2e18;
int n, maxg, ans, prefp[nmax + 5], prefg[nmax + 5];
struct T {
int p, g;
};
T a[nmax + 5];
bool ok(int i, int crtg, int crtp) {
int best = 0;
int l = i, r = n;
while (l <= r) {
int mid = (l + r) / 2;
int g = prefg[mid] - prefg[i];
int p = prefp[mid] - prefp[i];
if (crtg + g <= maxg) {
int totalg = crtg + g;
int totalp = crtp + p;
if (i + 1 <= n) {
totalp += (min(maxg - totalg, a[i + 1].g) / a[i + 1].g) * a[i + 1].p;
}
best = totalp;
l = mid + 1;
} else {
r = mid - 1;
}
}
return crtg + best > ans;
}
void bkt(int i, int crtg, int crtp) {
if (!ok(i - 1, crtg, crtp)) {
return;
}
if (i == n + 1) {
ans = max(ans, crtp);
return;
}
bkt(i + 1, crtg, crtp);
bkt(i + 1, crtg + a[i].g, crtp + a[i].p);
}
signed main() {
cin.tie(nullptr)->sync_with_stdio(false);
#ifdef LOCAL
freopen("file.in", "r", stdin);
freopen("file.out", "w", stdout);
#else
freopen("rucsac.in", "r", stdin);
freopen("rucsac.out", "w", stdout);
#endif
cin >> n >> maxg;
for (int i = 1; i <= n; i++) {
cin >> a[i].g >> a[i].p;
}
sort(a + 1, a + 1 + n, [&](T x, T y) {
return x.p * y.g > y.p * x.g;
});
for (int i = 1; i <= n; i++) {
prefp[i] = prefp[i - 1] + a[i].p;
prefg[i] = prefg[i - 1] + a[i].g;
}
int crtg = 0;
for (int i = 1; i <= n; i++) {
if (a[i].g + crtg <= maxg) {
ans += a[i].p;
crtg += a[i].g;
}
}
// for (int i = 1; i <= n; i++) {
// cout << a[i].g << ' ' << a[i].p << '\n';
// }
// cout << ans << '\n';
bkt(1, 0, 0);
cout << ans;
}