Pagini recente » Cod sursa (job #2144559) | Cod sursa (job #1531971) | Cod sursa (job #562947) | Cod sursa (job #2808729) | Cod sursa (job #3170975)
#include <iostream>
#include <cstdio>
#include <vector>
#include <functional>
#include <sstream>
#include <algorithm>
#include <ctime>
#include <chrono>
using namespace std;
#define w first
#define v second
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].w-sufpart[st].w<=wmax)rez=st;
break;
}
mid=(st+dr)/2;
if(sufpart[poz].w-sufpart[mid].w<=wmax)rez=mid,st=mid+1;
else dr=mid;
}
return sufpart[poz].v-sufpart[rez].v+obj[rez].v*(wmax-sufpart[poz].w+sufpart[rez].w)/obj[rez].w;
}
void bkt(ll poz)
{
//cerr<<clock()-start_time<<endl;
if(clock()-start_time>=195*CLOCKS_PER_SEC){cout<<VMAX;exit(0);}
if(poz==n)
{
VMAX=max(VMAX,vtot);
return;
}
//cerr<<poz<<endl;
bkt(poz+1);
wtot+=obj[poz].w;
if(wtot>W)return wtot-=obj[poz].w,void();
vtot+=obj[poz].v;
if(vtot+greedsuf(poz+1,W-wtot)<=VMAX)return wtot-=obj[poz].w,vtot-=obj[poz].v,void();
bkt(poz+1);
wtot-=obj[poz].w;
vtot-=obj[poz].v;
}
int main()
{
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].w>>obj[i].v;
sort(obj,obj+n,[&](pll a,pll b){return a.v*b.w>b.v*a.w;});
obj[n].w=1;
for(i=n-1;i>=0;i--)sufpart[i]=make_pair(sufpart[i+1].w+obj[i].w,sufpart[i+1].v+obj[i].v);
x=VMAX=0;
for(i=0;i<n;i++)
{
x+=obj[i].w;
if(x<=W)VMAX+=obj[i].v;
else break;
}
vtot=0;
wtot=0;
bkt(0);
cout<<VMAX;
return 0;
}