Cod sursa(job #1013005)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 20 octombrie 2013 00:45:04
Problema Problema rucsacului Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <cstdio>
#include <algorithm>

using namespace std;
const int Gmax = 10005;
int DP[ 2 ][ Gmax ],N,G,g;

void scan(int &A)
{
    char c = 0;
    A = 0;
    do
    {
        c = fgetc(stdin);
        if('0'<= c && c <= '9')
            A = A * 10 + c - 48;
    }while('0'<= c && c <= '9');
}

void read(){
    scan(N),scan(G);
}
void initial(){
    int w,p;
    scan(w),scan(p);
    DP[0][w] = p; // asta e optima
    g = w;
}

void solve(){

    int i,j,w,p,sol = -1,gnou;
    for( i = 1 ; i < N  ; ++ i){
        scan(w),scan(p);gnou = g;

        DP[i&1][w] = max (DP[!(i&1)][w] , p);
        for(j = 0; j <= g; ++j){

            DP[i&1][j] = max ( DP[!(i&1)][j] , DP[i&1][j]); // mostenim

            if( DP[ !(i&1) ][j] && j+w <= G){

                DP[i&1][j + w] = max( DP[!(i&1)][j] + p , DP[i&1][j+w]);
                if( g < j + w) gnou = j + w;
            }
        }
        g = gnou;
    }
    for(int i = 1; i <= Gmax ; ++i)
        sol = max ( sol , DP[ (N-1) & 1][i]);
    printf("%d",sol);
}

int main()
{
    freopen("rucsac.in","r",stdin);
    freopen("rucsac.out","w",stdout);

    read();
    initial();
    solve();

    return 0;
}