Cod sursa(job #2537571)

Utilizator XsoundCristian-Ioan Roman Xsound Data 3 februarie 2020 19:36:36
Problema Problema rucsacului Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>
#define Nmax 5005
using namespace std;
ifstream fin ( "rucsac.in" );
ofstream fout ( "rucsac.out" );

struct obiect
{
    int g, p;
};

void read ( );
void solve ( );

int calculez ( int i, int g );

inline bool cmp ( obiect &a, obiect &b );

obiect v[Nmax];

int n, g;

int main ( )
{
    read ( );

    solve ( );
}

void solve ( )
{
    int p, P = 0;

    sort ( v+1, v+n+1, cmp );

    for ( int i = 1; i <= n; i++ )
    {
        if ( g < v[i].g )
            continue;

        p = v[i].p;

        p += calculez ( i+1, g-v[i].g );

        if ( P < p )
            P = p;
    }

    fout << P;
}

int calculez ( int i, int g )
{
    if ( g == 0 )
        return 0;
    else if ( i == n+1 )
        return 0;
    while ( v[i].g > g )
        i++;

    int x = 0;

    for (; i <= n; i++ )
        x = max ( x, calculez ( i+1, g-v[i].g ) + v[i].p );

    return x;
}

inline bool cmp ( obiect &a, obiect &b )
{
    if ( a.p > b.p )
        return 1;
    else if ( a.p == b.p && a.g < b.g )
        return 1;
    return 0;
}

void read ( )
{
    fin >> n >> g;

    for ( int i = 1; i <= n; i++ )
        fin >> v[i].g >> v[i].p;
}