Cod sursa(job #3170987)

Utilizator CobzaruAntonioCobzaru Paul-Antonio CobzaruAntonio Data 18 noiembrie 2023 11:52:54
Problema Problema rucsacului Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <iostream>
#include <algorithm>
using namespace std;
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 = (long double)x.second/ (long double)x.first;
    a2 =  (long double)y.second/ (long double)y.first;
    return a1 > a2;
}
long double greedyp(int pos,int G)
{
    long double rasp = 0;
    int g = 0;
    for(int i=pos;i<=n;i++)
    {
        if(g+ob[i].first > G)
        {
            long double coef = (long double)(G-g)/(long double)ob[i].first;
            rasp+=coef*(long double)ob[i].second;
            break;
        }
        g+=ob[i].first;
        rasp+=ob[i].second;
    }
    return rasp;
}
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+greedyp(pos+1,W-w)<=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;
    }
    for(int i=n;i>=1;i--)
        ptot[i]=ptot[i+1]+ob[i].second;
    bkt(1);
    cout << pmax;
    return 0;
}