Cod sursa(job #1916726)

Utilizator hunix94Karaman Hunor hunix94 Data 9 martie 2017 10:13:47
Problema Problema rucsacului Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>

using namespace std;

int n, G;

struct item {
    int w;
    int p;
};

vector<item> items;

void beolvas() {
    int w, p;
    ifstream input("rucsac.in");
    input >> n >> G;
    items.resize(n);
    for (int i = 0; i < n; i++) {
        input >> w >> p;
        items[i].w = w;
        items[i].p = p;
    }
    input.close();
}

int main() {
    beolvas();

    int mat[2][G + 1];

    //Init

    for (int y = 0; y < 2; y++) {
        for (int x = 0; x <= G; x++) {
            mat[y][x] = 0;
        }
    }

    mat[0][items[0].w] = items[0].p;

    item c;

    for (int i = 1; i < n; i++) {
        c = items[i];
        mat[1][c.w] = max(mat[0][c.w], c.p);

        for (int j = 1; j <= (G - c.w); j++) {
            if (mat[0][j] > 0) {
                int s = mat[0][j] + c.p;
                mat[1][j + c.w] = max(s, mat[0][c.w]);
            }
        }

        for (int j = 1; j <= G; j++) {
            mat[0][j] = mat[1][j];
        }
    }

    ofstream output("rucsac.out");
    output << mat[1][G] << endl;
    output.close();

    return 0;
}