Cod sursa(job #1121390)

Utilizator ralucik_2006Filimon Raluca Elena ralucik_2006 Data 25 februarie 2014 12:43:55
Problema Problema rucsacului Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

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

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++)
      for (j=0;j<=gr;j++)
      best[i][j]=-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[i-1][pz]!=-1) best[i][j]=best[i-1][pz]+a[i].p;
           if (best[i][j]<best[i-1][j]) best[i][j]=best[i-1][j];
       }
    mx=-1;
    for (i=1;i<=gr;i++)
    if (mx<best[n][i]) mx=best[n][i];
    g<<mx;
    return 0;
}