Cod sursa(job #3235697)

Utilizator popescu_georgePopescu George popescu_george Data 20 iunie 2024 15:13:30
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.39 kb
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
using namespace std;
int n,W,suf,i,j,k,VMAX,x,y,z,t;
pair<int,int> 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;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long 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);
        return;
    }
    //cerr<<poz<<endl;
    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);
    if(vtot+greedsuf(poz+1,rem)>VMAX)
        bkt(poz+1,vtot,rem);
}
bool comp(const pair<int,int>&a,const pair<int,int>&b){return a.second*b.first>=b.second*a.first;}
int main()
{
    //ios::sync_with_stdio(false);
    //cin.tie(nullptr);
    //freopen("rucsac.in","r",stdin);
    //freopen("rucsac.out","w",stdout);
    InParser fin("rucsac.in");
    //ifstream 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,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;
    }
    bkt(0,0,W);
    fout<<VMAX;
	return 0;
}