Cod sursa(job #639014)

Utilizator oanasiadriOana Tivadar oanasiadri Data 22 noiembrie 2011 09:27:53
Problema Problema rucsacului Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 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, lc,lp, g, p, c, pn, 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[l].g,
   cu varianta optima obtinuta prin plasarea a l-1 obiecte intr-un rucsac cu capacitate c-a[l].g. */

int main() {
	fi >> n >> G;
	for (lc = 0; lc <= 1; lc++)
		fi >> a[lc].g >> a[lc].p;
	for (lc = 0; lc <= 1; lc++) {
    for (c = 1; c <= G; c++) {
      if (a[lc].g <= c) {               // Obiectul curent incape in rucsac?
        pn = a[lc].p+mp[lp][c-a[lc].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 l-1 obiecte.
      }
      else
        mp[lc][c] = mp[lp][c];         // Retinem profitul obtinut cu primele l-1 obiecte.
      /*cout << setw(4) << mp[lc][c];   // Daca vrem sa vedem matricea pe ecran. */
    }
    /*cout << endl;                    // Daca vrem sa vedem matricea pe ecran. */
	}
	fo << mp[n][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
*/