Cod sursa(job #2975996)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 7 februarie 2023 22:44:54
Problema Problema rucsacului Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.75 kb
#include <cstdio>
#include <vector>

using namespace std;

int knapsack(const vector<pair<int,int>>& objects, int knapsackSize) {
  vector<int> DP(knapsackSize + 1, -1);
  DP[0] = 0;
  int maxProfit = -1;
  for (auto obj: objects)
    for (int i = knapsackSize; i >= obj.first; --i)
      if (DP[i - obj.first] != -1) {
	DP[i] = max(DP[i], DP[i - obj.first] + obj.second);
	maxProfit = max(maxProfit, DP[i]);
      }
  return maxProfit;
}

int main() {
  freopen("rucsac.in", "r", stdin);
  freopen("rucsac.out", "w", stdout);

  int N, K;
  vector<pair<int,int>> objects;

  scanf("%d%d", &N, &K);
  objects.resize(N);
  for (int i = 0; i < N; ++i)
    scanf("%d%d", &objects[i].first, &objects[i].second);
  
  printf("%d\n", knapsack(objects, K));
  
  return 0;
}