Cod sursa(job #3171027)

Utilizator poparobertpoparobert poparobert Data 18 noiembrie 2023 12:07:03
Problema Problema rucsacului Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <functional>
#include <sstream>
#include <algorithm>
#include <ctime>
#include <chrono>
using namespace std;
//clock_t start_time=clock(),end_time;
typedef int ll;
typedef pair<ll,ll> pll;
ll n,W,suf,i,j,k,VMAX,x,y,z,t,vtot,wtot;
pll obj[5002],sufpart[5002];
ll greedsuf(ll poz,ll wmax)
{
    if(poz==n)return 0;
    ll st=poz+1,dr=n,mid,rez=st;
    while(true)
    {
        //cerr<<st<<' '<<dr<<endl;
        if(st==dr)
        {
            if(sufpart[poz].first-sufpart[st].first<=wmax)rez=st;
            break;
        }
        mid=(st+dr)/2;
        if(sufpart[poz].first-sufpart[mid].first<=wmax)rez=mid,st=mid+1;
        else dr=mid;
    }
    return sufpart[poz].second-sufpart[rez].second+obj[rez].second*(wmax-sufpart[poz].first+sufpart[rez].first)/obj[rez].first;
}
long long getTime(){return chrono::steady_clock::now().time_since_epoch().count(); }
long long startTime;
void bkt(ll poz)
{
     //if((getTime()-startTime)/1000000 >= 201)     {         cout << VMAX;         exit(0);     }
    //cerr<<clock()-start_time<<endl;
    //if(clock()-start_time>=1*CLOCKS_PER_SEC){cout<<VMAX;exit(0);}
    if(poz==n)
    {
        VMAX=max(VMAX,vtot);
        return;
    }
    //cerr<<poz<<endl;
    bkt(poz+1);
    wtot+=obj[poz].first;
    if(wtot>W)
    {
        wtot-=obj[poz].first;
        return ;
    }
    vtot+=obj[poz].second;
    if(vtot+sufpart[poz+1].second<VMAX||vtot+greedsuf(poz+1,W-wtot)<=VMAX)
    {
        wtot-=obj[poz].first,vtot-=obj[poz].second;
        return ;
    }
    bkt(poz+1);
    wtot-=obj[poz].first;
    vtot-=obj[poz].second;
}
int main()
{
    startTime=getTime();
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    freopen("rucsac.in","r",stdin);
    freopen("rucsac.out","w",stdout);
    cin>>n>>W;
    for(i=0;i<n;i++)cin>>obj[i].first>>obj[i].second;
    sort(obj,obj+n,[&](pll a,pll b){return a.second*b.first>b.second*a.first;});
    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;
    }
    vtot=0;
    wtot=0;
    bkt(0);
    cout<<VMAX;
	return 0;
}