Cod sursa(job #639125)

Utilizator juniorOvidiu Rosca junior Data 22 noiembrie 2011 15:40:54
Problema Problema rucsacului Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
/* 50 p pe infoarena */

#include <fstream>
#include <iostream>
#include <iomanip>

using namespace std;

struct obiect {
	int g, p;
};

obiect a[5001];
int n, G, l, g, p, c, pn, lp, lc, mp[2][10001];
ifstream fi ("rucsac.in");
ofstream fo ("rucsac.out");

/* Ideea de rezolvare:
   Pentru un rucsac de capacitate c, asociem obiectul curent (l), avand greutatea a[lc].g,
   cu varianta optima obtinuta prin plasarea a lp obiecte intr-un rucsac cu capacitate c-a[lc].g. */

int main() {
	fi >> n >> G;
	for (l = 1; l <= n; l++)
		fi >> a[l].g >> a[l].p;
  lp = 0; lc = 1;
	for (l = 1; l <= n; l++) {
    for (c = 1; c <= G; c++) {
      if (a[l].g <= c) {               // Obiectul curent incape in rucsac?
        pn = a[l].p+mp[lp][c-a[l].g]; // profitul nou
        if (pn > mp[lp][c])           // Avem profit mai bun folosind obiectul curent?
          mp[lc][c] = pn;               // Retinem profitul nou.
        else
          mp[lc][c] = mp[lp][c];       // Retinem profitul obtinut cu primele lp obiecte.
      }
      else
        mp[lc][c] = mp[lp][c];         // Retinem profitul obtinut cu primele lp obiecte.
      /*cout << setw(4) << mp[lc][c];   // Daca vrem sa vedem matricea pe ecran. */
    }
    lp = 1-lp; lc = 1-lc;
	}
	fo << mp[lp][G];                      // Am folosit toate obiectele si capacitatea integrala a ruscacului.
	return 0;
}



/* Exemplu de fisier de date:
4 10
2 20
3 40
6 50
4 45
*/