Pagini recente » Cod sursa (job #2757410) | Cod sursa (job #599123) | Cod sursa (job #1350124) | Cod sursa (job #2467859) | Cod sursa (job #3161235)
#include <fstream>
using namespace std;
ifstream fin("rucsac.in");
ofstream fout("rucsac.out");
// 1 ≤ N ≤ 5000
// 1 ≤ G ≤ 10000
// 0 ≤ Wi, Pi ≤ 10000
const int MAX_N = 5001;
const int MAX_G = 10001;
// dp(idx, capacitate)
// fiind global, toate valorile matricei
// sunt deja inițializate cu 0
int dp[MAX_N][MAX_G];
struct t_object {
int greutate;
int profit;
};
int main() {
int nr_elem;
int gmax;
t_object objs[MAX_N];
fin >> nr_elem >> gmax;
for (int i = 1; i <= nr_elem; i++) {
int greutate;
int profit;
fin >> greutate >> profit;
t_object obj = {greutate, profit};
objs[i] = obj;
}
// cazul idx == 0 este deja acoperit
// din moment ce matricea a fost declarată global
// cazul greutate == 0 este deja acoperit
// din moment ce matricea a fost declarată global
for (int idx = 1; idx <= nr_elem; idx++) {
for (int g = 1; g <= gmax; g++) {
t_object obj = objs[idx];
if (obj.greutate > g) {
// nu are loc în ghiozdan
dp[idx][g] = dp[idx - 1][g];
} else {
// are loc în ghiozdan
// considerăm două cazuri
// cazul 1 - nu îl punem în ghiozdan
int profit1 = dp[idx - 1][g];
// cazul 2 - îl punem în ghiozdan
int profit2 = obj.profit + dp[idx - 1][g - obj.greutate];
dp[idx][g] = max(profit1, profit2);
}
}
}
fout << dp[nr_elem][gmax] << endl;
return 0;
}