Cod sursa(job #3171931)

Utilizator poparobertpoparobert poparobert Data 19 noiembrie 2023 19:41:51
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.07 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)
{
    ll 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;
}
//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;
    wtot+=obj[poz].first;
    vtot+=obj[poz].second;
    if(wtot>W||vtot+sufpart[poz+1].second<VMAX||vtot+greedsuf(poz+1,W-wtot)<=VMAX)
    {
        wtot-=obj[poz].first,vtot-=obj[poz].second;
        bkt(poz+1);
        return;
    }
    if(wtot+sufpart[poz+1].first<=W){VMAX=max(vtot+sufpart[poz+1].second,VMAX);return;}
    bkt(poz+1);
    wtot-=obj[poz].first;
    vtot-=obj[poz].second;
    bkt(poz+1);
}
bool comp(pair<int,int>a,pair<int,int>b){return a.second*b.first>=b.second*a.first;}
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,comp);
    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;
}