Cod sursa(job #1553323)

Utilizator sulzandreiandrei sulzandrei Data 19 decembrie 2015 16:25:31
Problema Problema rucsacului Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
ifstream in("rucsac.in");
ofstream out("rucsac.out");
int solutie_2G_memorie(int n, int G, int w[], int p[])
{
    int cost2[2][G+1];
    for(int g = 0 ; g <= G ; g++)
        cost2[0][g] = 0;
    for(int i = 1 ; i <= n ; i ++)
    {
        cost2[1][0] = 0;
        for(int g = 1 ; g <= G ; g ++)
            if (w[i]<= g)
                cost2[1][g] = max(p[i] + cost2[0][g-w[i]] , cost2[0][g]);
            else
                cost2[1][g] = cost2[0][g];
        for(int g = 1 ; g <= G ; g ++)
            cost2[0][g] = cost2[1][g];
    }
    return cost2[1][G];
}
int solutie_nG_memorie(int n, int G,int w[], int p[])
{
    int cost[n+1][G+1];
    for(int g = 0 ; g <= G ; g++)
        cost[0][g] = 0;
    for(int i = 1 ; i <= n ; i ++)
    {
        cost[i][0] = 0;
        for(int g = 1 ; g <= G ; g ++)
            if (w[i] <= g)
                cost[i][g] = max(p[i] + cost[i-1][g-w[i]],cost[i-1][g]);
            else
                cost[i][g] = cost[i-1][g];
    }
    return cost[n][G];
}
int main()
{
    int n,G;
    in >> n >> G;
    int w[n+1],
        p[n+1];
    for(int i = 1 ; i <= n ; i ++)
        in >> w[i] >> p[i];
    //out << solutie_nG_memorie(n,G,w,p);
    out << solutie_2G_memorie(n,G,w,p);


    return 0;
}