Cod sursa(job #3170918)

Utilizator CobzaruAntonioCobzaru Paul-Antonio CobzaruAntonio Data 18 noiembrie 2023 11:14:36
Problema Problema rucsacului Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream cin("rucsac.in");
ofstream cout("rucsac.out");
int W;
int n,wmax,pmax;
int w,p;
int ptot[10005];
pair<int,int> ob[10005];
bool fcmp2 (pair<int,int> x, pair<int,int> y)
{
    if(x.first > y.first)
        return true;
    else if (x.first == y.first)
        return x.second > y.second;
    return false;
}
bool fcmp1 (pair<int,int> x, pair<int,int> y)
{
    long double a1,a2;
    a1 = x.second/x.first;
    a2 = y.second/y.first;
    return a1 > a2;
}
void bkt(int pos)
{
    if(pos==n+1)
    {
        if(p>pmax)
        {
            pmax = p;
            wmax = w;
        }
        return;
    }
    bkt(pos+1);
    w+=ob[pos].first;
    p+=ob[pos].second;
    if(w>W || p + ptot[pos+1]<=pmax)
    {
        p-=ob[pos].second;
        w-=ob[pos].first;
        return;
    }
    bkt(pos+1);
    p-=ob[pos].second;
    w-=ob[pos].first;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> W;
    for(int i=1;i<=n;i++)
        cin >> ob[i].first >> ob[i].second;
    sort(ob+1,ob+n+1,fcmp1);
    for(int i=1;i<=n;i++)
    {
        if(wmax+ob[i].first > W)
            continue;
        wmax+=ob[i].first;
        pmax+=ob[i].second;
    }
    sort(ob+1,ob+n+1,fcmp2);
    for(int i=n;i>=1;i--)
        ptot[i]=ptot[i+1]+ob[i].second;
    bkt(1);
    cout << pmax;
    return 0;
}