Cod sursa(job #3004930)

Utilizator andreea_chivuAndreea Chivu andreea_chivu Data 16 martie 2023 18:07:27
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <iostream>
#include <fstream>

using namespace std;

const int NMAX = 5005;
const int GMAX = 10005;

int p[NMAX];
int w[NMAX];
int profit[GMAX];
int ant[GMAX];

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

    int n, g;
    fin >> n >> g;

    for(int i = 1; i <= n; i++){
        fin >> w[i] >> p[i];
    }

    for(int i = 0; i <= n; i++)
        ant[i] = 0;

    for(int i = 1; i <= n; i++){ // imi selectez din primele i obiecte
        for(int j = 1; j <= g; j++){ //greutatea maxima
            if(j >= w[i])
                profit[j] = max(ant[j], ant[j - w[i]] + p[i]);
            else
                profit[j] = ant[j];
        }
        for(int j = 1; j <= g; j++){
            ant[j] = profit[j];
        }
    }

    fout << profit[g];



    fin.close();
    fout.close();
    return 0;
}