Cod sursa(job #3324359)

Utilizator BuruianaRaresAndreiBuruiana Rares Andrei BuruianaRaresAndrei Data 22 noiembrie 2025 10:08:44
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.71 kb
#include <bits/stdc++.h>

#define int long long
#define pii pair<int, int>
#define fs first
#define sd second

using namespace std;

ifstream in("rucsac.in");
ofstream out("rucsac.out");

void solve() {

}

bool customSort(pii a, pii b) {
    if(a.sd * b.fs == b.sd * a.fs) {
        return a.fs < b.fs;
    }
    else {
        return a.sd * b.fs > b.sd * a.fs;
    }
}

int n, g, pmax;
pii v[5005], sp[5005];

bool check(int pos, int pcrt, int gcrt) {
    int st = pos, dr = n, ans = pos - 1;
    while(st <= dr) {
        int mij = (st + dr) / 2;
        if(sp[mij].fs - sp[pos - 1].fs + gcrt <= g) {
            ans = mij;
            st = mij + 1;
        }
        else {
            dr = mij - 1;
        }
    }

    // cout << pos - 1 << ' ' << pcrt << ' ' << gcrt << ' ' << ans << ' ' << sp[ans].sd - sp[pos - 1].sd << ' ' << sp[ans].fs - sp[pos - 1].fs << ' ';

    pcrt += sp[ans].sd - sp[pos - 1].sd;
    gcrt += sp[ans].fs - sp[pos - 1].fs;

    // cout << (double)(pcrt) + ((double)(g - gcrt) / (double)(v[ans + 1].fs)) * (double)(v[ans + 1].sd) << ' ' << (double) pmax << '\n';

    if(ans == n) return true;
    return (double)(pcrt) + ((double)(g - gcrt) / (double)(v[ans + 1].fs)) * (double)(v[ans + 1].sd) > (double)(pmax);
}

void bkt(int pos, int pcrt, int gcrt) {
    pmax = max(pmax, pcrt);

    // cout << pos << ' ' << pcrt << ' ' << pmax << '\n';

    if(pos == n + 1) {
        return;
    }

    for(int take = 1; take >= 0; take--) {
        if(take == 1 && gcrt + v[pos].fs <= g) {
            pcrt += v[pos].sd;
            gcrt += v[pos].fs;

            if(check(pos + 1, pcrt, gcrt))
                bkt(pos + 1, pcrt, gcrt);

            pcrt -= v[pos].sd;
            gcrt -= v[pos].fs;
        }
        else if(take == 0) {
            if(check(pos + 1, pcrt, gcrt))
                bkt(pos + 1, pcrt, gcrt);
        }
    }
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    /*
    int t = 1; cin >> t;
    while(t--) {
        solve();
    }
    */


    in >> n >> g;
    for(int i = 1; i <= n; i++) {
        in >> v[i].fs >> v[i].sd;
    }
    sort(v + 1, v + n + 1, customSort);
/*
    for(int i = 1; i <= n; i++) {
        cout << v[i].fs << ' ' << v[i].sd << '\n';
    }
    cout << '\n';
*/
    for(int i = 1; i <= n; i++) {
        sp[i] = {sp[i - 1].fs + v[i - 1].fs, sp[i - 1].sd + v[i - 1].sd};
    }
    sp[n + 1] = sp[n];
    pmax = 0;
    int crtcost = 0;
    for(int i = 1; i <= n; i++) {
        if(crtcost + v[i].fs <= g) {
            pmax += v[i].sd;
            crtcost += v[i].fs;
        }
    }

    bkt(1, 0, 0);

    out << pmax << '\n';

    return 0;
}