Cod sursa(job #3235705)

Utilizator popescu_georgePopescu George popescu_george Data 20 iunie 2024 15:47:41
Problema Problema rucsacului Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include<bits/stdc++.h>
using namespace std;
#define P pair<int,int>
int n,w,u,i,j,k,v,x,y,z,t;
P o[5002],t[5002];
class I
{
    private:
        FILE *F;
        char *b;
        int p;
        char C()
        {
            if(++p==4096)
                fread(b,1,4096,F),p=0;
            return b[p];
        }
    public:
        I(const char* e)
        {
            F=fopen(e,"r");
            b=new char[4096]();
            p=4095;
        }
        I &operator>>(int &n)
        {
            char c;
            for(c=C();!isdigit(c);c=C());
            for(n=0;isdigit(c);n=10*n+c-'0',c=C());
            return *this;
        }
};
int D(int O,int E)
{
    int R=0;
    for(;O<n&&o[O].first<E;R+=o[O].second,E-=o[O++].first);
    return O==n?R:R+o[O].second*E/o[O].first;
}
void B(int O,int Z,int W)
{
    if(O==n)
        v=max(v,Z);
    else {
        if(W>=o[O].first&&Z+o[O].second+D(O+1,W-o[O].first)>v)
            B(O+1,Z+o[O].second,W-o[O].first);
        if(Z+D(O+1,W)>v)
            B(O+1,Z,W);
    }
}
bool A(P a,P b)
{
    return a.second*b.first>=b.second*a.first;
}
int main()
{
    I F("rucsac.in");
    ofstream G("rucsac.out");
    for(F>>n>>w;i<n;F>>o[i].first>>o[i].second,++i);
    for(sort(o,o+n,A),o[n].first=1,i=n-1;i>=0;t[i]=make_pair(t[i+1].first+o[i].first,t[i+1].second+o[i].second),--i);
    for(i=0;i<n&&x+o[i].first<=w;x+=o[i].first,v+=o[i++].second);
    return B(0,0,w),G<<v,0;
}