Cod sursa(job #1591130)

Utilizator firewavesBirsu Ion firewaves Data 5 februarie 2016 19:58:57
Problema Problema rucsacului Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;

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

int main()
{
    int n, g, i, j, maxim = 0;
    int **profit;
    int prf, grt;

    fin >> n >> g;

    profit =(int**) calloc(n, sizeof(int *));
    profit[0] =(int*) calloc(g, sizeof(int));

    for(i = 0; i < n; i++){
            fin >> grt >> prf;
            if(i == 0 && grt <= g)
                profit[0][grt-1] = prf;
            else{
                profit[i] =(int*) calloc(g, sizeof(int));
                for(j = 0 ; j < g; j++)
                {
                    if( profit[i][j] == 0)
                    profit[i][j] = profit[i-1][j];
                    if(profit[i-1][j] != 0 && j+grt <=g && profit[i-1][j+grt] < profit[i-1][j] + prf)
                        profit[i][j+grt] =  profit[i-1][j] + prf;
                }
                if(profit[i][grt-1] < prf)
                    profit[i][grt-1] = prf;
                free(profit[i-1]);

            }
    }
    fin.close();
    for(i = 0; i < g; i++)
        if(maxim < profit[n-1][i])
        maxim = profit[n-1][i];
    fout << maxim;
    fout.close();
    return 0;
}