Cod sursa(job #2891110)

Utilizator bucketlover413Sodinca Iulia Cristiana bucketlover413 Data 17 aprilie 2022 16:00:06
Problema Problema rucsacului Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <iostream>
#include <fstream>


using namespace std;

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

int  k, st[10000];
int n, g;

struct obiect
{
    int val;
    int greu;
} obj[10001], total, max_total;

bool Valid(int k) //ia toate valorile din stiva si le compara cu valorile de pe nivelul k
{
    int i;
    for(i=1; i<k; i++)
        if(st[k]==st[i])
            return 0;
    //  cout<<total.greu<<" "<<total.val<<endl;
    if(total.greu>g)
        //{cout<<"prea mare"<<endl;
        return 0;
    return 1;
}

void Back(int k)
{
    int i;
    for(i=1; i<=n; i++)
    {
        st[k]=i;
        total.val=0;
        total.greu=0;
        for(int j=1; j<=k; j++)
        {
            total.val+=obj[st[j]].val;
            total.greu+=obj[st[j]].greu;
        }

        if(Valid(k))
        {


            if(total.val>max_total.val)
            {
                max_total.val=total.val;
                max_total.greu=total.greu;
            }

            else
                Back(k+1);
        }

    }
}


int main()
{
    fin>>n>>g;
    for(int i=1; i<=n; i++)
        fin>>obj[i].greu>>obj[i].val;
    Back(1);

    fout<<max_total.val;
    return 0;
}