Cod sursa(job #3373490)

Utilizator matyrobbrtMaty Robbrt matyrobbrt Data 7 noiembrie 2026 10:47:50
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <bits/stdc++.h>
#define ull unsigned long long
using namespace std;

ifstream fin("rucsac.in");
ofstream fout("rucsac.out");

struct Item {
    int w, v;

    bool operator<(const Item &other) const {
        return ((float) v) / (float) w > ((float) other.v) / (float) other.w;
    }
};

int maxValueAfter(const vector<Item> &items, int i, int remainingCapacity) {
    int maxValue = 0;
    for (int j = i; j < items.size(); j++) {
        if (remainingCapacity >= items[j].w) {
            maxValue += items[j].v;
            remainingCapacity -= items[j].w;
        } else {
            maxValue += (int) ceil((double) items[j].v * remainingCapacity / items[j].w);
            break;
        }
    }
    return maxValue;
}

void backtrack(vector<Item> &items, vector<int> &profits, int i, int remainingCapacity, ull currentProfit,
               ull &maxProfit) {
    if (currentProfit > maxProfit) {
        maxProfit = currentProfit;
    }
    if (i >= items.size()) return;
    if (currentProfit + profits.back() - profits[i] <= maxProfit) return;
    if (currentProfit + maxValueAfter(items, i, remainingCapacity) <= maxProfit) return;

    if (remainingCapacity - items[i].w >= 0) {
        backtrack(items, profits, i + 1, remainingCapacity - items[i].w, currentProfit + items[i].v, maxProfit);
    }
    backtrack(items, profits, i + 1, remainingCapacity, currentProfit, maxProfit);
}

int main() {
    int n, gmax;
    fin >> n >> gmax;
    vector<Item> v(n);
    for (int i = 0; i < n; i++) {
        fin >> v[i].w >> v[i].v;
    }

    sort(v.begin(), v.end());

    vector<int> profits(n + 1, 0);
    for (int i = 0; i < n; i++) {
        profits[i + 1] = v[i].v + profits[i];
    }

    ull maxProfit = 0;
    backtrack(v, profits, 0, gmax, 0, maxProfit);

    fout << maxProfit;
}