Cod sursa(job #3235698)

Utilizator popescu_georgePopescu George popescu_george Data 20 iunie 2024 15:20:43
Problema Problema rucsacului Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.17 kb
#include<bits/stdc++.h>
using namespace std;
#define P pair<int,int>
int n,W,suf,i,j,k,VMAX,x,y,z,t;
P obj[5002],sufpart[5002];
class InParser
{
    private:
        FILE *fin;
        char *buff;
        int sp;
        char read_ch()
        {
            ++sp;
            if (sp == 4096) {
                sp = 0;
                fread(buff, 1, 4096, fin);
            }
            return buff[sp];
        }
    public:
        InParser(const char* nume)
        {
            fin = fopen(nume, "r");
            buff = new char[4096]();
            sp = 4095;
        }
        InParser& operator >> (int &n)
        {
            char c;
            while (!isdigit(c = read_ch()) && c != '-');
            int sgn = 1;
            if (c == '-') {
                n = 0;
                sgn = -1;
            } else {
                n = c - '0';
            }
            while (isdigit(c = read_ch())) {
                n = 10 * n + c - '0';
            }
            n *= sgn;
            return *this;
        }
};
int greedsuf(int poz,int wmax)
{
    int rez=0;
    while(poz<n&&obj[poz].first<wmax)
        rez+=obj[poz].second,wmax-=obj[poz++].first;
    if(poz==n)
        return rez;
    return rez+obj[poz].second*wmax/obj[poz].first;
}
void bkt(int poz,int vtot,int rem)
{
    if(poz==n)
        VMAX=max(VMAX,vtot);
    else if(rem-obj[poz].first>=0&&vtot+obj[poz].second+greedsuf(poz+1,rem-obj[poz].first)>VMAX)
        bkt(poz+1,vtot+obj[poz].second,rem-obj[poz].first);
    else if(vtot+greedsuf(poz+1,rem)>VMAX)
        bkt(poz+1,vtot,rem);
}
bool A(P a,P b)
{
    return a.second*b.first>=b.second*a.first;
}
int main()
{
    InParser fin("rucsac.in");
    ofstream fout("rucsac.out");
    fin>>n>>W;
    for(i=0;i<n;i++)
        fin>>obj[i].first>>obj[i].second;
    sort(obj,obj+n,A),obj[n].first=1;
    for(i=n-1;i>=0;i--)
        sufpart[i]=make_pair(sufpart[i+1].first+obj[i].first,sufpart[i+1].second+obj[i].second);
    x=VMAX=0;
    for(i=0;i<n;i++) {
        x+=obj[i].first;
        if(x<=W)
            VMAX+=obj[i].second;
        else
            break;
    }
    return bkt(0,0,W),fout<<VMAX,0;
}