Cod sursa(job #3161239)

Utilizator TheooTeodora Dogeanu Theoo Data 26 octombrie 2023 10:09:52
Problema Problema rucsacului Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int MAX_N=5001;
const int MAX_G=1001;
///dp(index, capacitate)
///find globag toate val mat sunt deja 0
int dp[MAX_N][MAX_G];

struct t_object{
    int greutate;
    int profit;
    };

int main()
{
    int nr_elem, gmax;
    t_object objs[MAX_N];

    fin>>nr_elem>>gmax;

    for(int i=1;i<=nr_elem; i++)
    {
        int greutate;
        int profit;
        fin>>greutate>>profit;
        t_object obj={greutate,profit};
        objs[i]=obj;
    }

    ///cazurile idx==0 si greutate==0
    ///sunt deja acoperite din moment ce matricea a fost declarata global

    for(int idx=1; idx<=nr_elem; idx++)
    {
        for(int g=1; g<=gmax; g++)
        {
            t_object obj=objs[idx];

            if(obj.greutate > g)
            {
                ///nu are loc in ghiozdan
                dp[idx][g]=dp[idx-1][g];
            }
            else
            {
                ///are loc in ghiozdan
                ///consideram 2 cazuri
                ///cazul 1 - nu l punem in ghiozdan
                int profit1 = dp[idx-1][g];

                ///cazul 2 - il punem in ghiozdan
                int profit2= obj.profit + dp[idx-1][g-obj.greutate];

                dp[idx][g]= max(profit1,profit2);
            }
        }
    }

    cout<<dp[nr_elem][gmax];
    return 0;
}