Cod sursa(job #638996)

Utilizator claudiugyulayGyulai Claudiu claudiugyulay Data 22 noiembrie 2011 08:20:05
Problema Problema rucsacului Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 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, mp[1500][1500];
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 (l = 1; l <= n; l++)
		fi >> a[l].g >> a[l].p;
	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[l-1][c-a[l].g]; // profitul nou
        if (pn > mp[l-1][c])           // Avem profit mai bun folosind obiectul curent?
          mp[l][c] = pn;               // Retinem profitul nou.
        else
          mp[l][c] = mp[l-1][c];       // Retinem profitul obtinut cu primele l-1 obiecte.
      }
      else
        mp[l][c] = mp[l-1][c];         // Retinem profitul obtinut cu primele l-1 obiecte.
      /*cout << setw(4) << mp[l][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
*/