Cod sursa(job #2576381)

Utilizator ardutgamerAndrei Bancila ardutgamer Data 6 martie 2020 18:54:27
Problema Problema rucsacului Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

ifstream fin("rucsac.in");
ofstream fout("rucsac.out");

const int NMAX = 5005;
const int INF = 2e9;
struct obiect {
	int profit, greutate;
};

obiect v[NMAX];
int dp[NMAX];

int n, g;

int main()
{
	fin >> n >> g;
	for (int i = 1; i <= g; i++)
		dp[i] = -INF;
	for (int i = 1; i <= n; i++)
		fin >> v[i].greutate >> v[i].profit;
	int last = 0;
	for (int i = 1; i <= n; i++)
	{
		for (int j = last; j >= 0; j--)
		{
			if (j + v[i].greutate <= g)
			{
				dp[j + v[i].greutate] = max(dp[j + v[i].greutate], dp[j] + v[i].profit);
				last = max(last, j + v[i].greutate);
				last = min(last, g);
			}
		}
	}
	int ma = 0;
	for (int i = 0; i <= g; i++)
		ma = max(ma, dp[i]);
	fout << ma << "\n";
	return 0;
}