Cod sursa(job #1121443)

Utilizator ralucik_2006Filimon Raluca Elena ralucik_2006 Data 25 februarie 2014 12:51:44
Problema Problema rucsacului Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <fstream>
#include <algorithm>

using namespace std;

int best[2][10001],i,n,gr,j,pz,mx;

struct obiect
{
    int w,p;
}a[5001];

int cmp (obiect A, obiect B)
{
    if (A.w<B.w) return 1;
    return 0;
}

int main()
{
    ifstream f("rucsac.in");
    ofstream g("rucsac.out");
    f>>n>>gr;
    for (i=1;i<=n;i++)
        f>>a[i].w>>a[i].p;
    sort (a+1,a+n+1,cmp);
    for (i=0;i<=n;i++)
      best[0][i]=best[1][i]=-1;
    best[0][0]=0;
    for (i=1;i<=n;i++)
    {
       for (j=0;j<=gr;j++)
       {
           pz=j-a[i].w;
           if (pz>=0)
            if(best[0][pz]!=-1) best[1][j]=best[0][pz]+a[i].p;
           if (best[1][j]<best[0][j]) best[1][j]=best[0][j];
       }
       for (j=0;j<=gr;j++)
       {
           best[0][j]=best[1][j];
           best[1][j]=-1;
       }
    }
    mx=-1;
    for (i=1;i<=gr;i++)
    if (mx<best[0][i]) mx=best[0][i];
    g<<mx;
    return 0;
}