Cod sursa(job #2666273)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 1 noiembrie 2020 12:42:59
Problema Energii Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1 kb
#include <iostream>
#include <fstream>
#include <algorithm>

const int NMAX = 1e3;
const int EMAX = 5e3;
const int INF = 1e9 + 7;

int n, target, energySum, sol = INF;
int e[1 + NMAX], c[1 + NMAX];
int dp[2][1 + EMAX];

void read() {
  std::ifstream in("energii.in");

  in >> n >> target;

  for (int i = 1; i <= n; ++i) {
    in >> e[i] >> c[i];
    energySum += e[i];
  }

  in.close();
}

int main() {
  read();

  std::ofstream out("energii.out");

  if (energySum < target) {
    out << "-1\n";
    out.close();
    return 0;
  }

  for (int i = 0; i < 2; ++i)
    for (int j = 0; j <= target; ++j)
      dp[i][j] = INF;
  dp[0][0] = 0;

  int lin = 1;
  for (int i = 1; i <= n; ++i, lin = 1 - lin) {
    for (int j = 0; j <= target; ++j) {
      dp[lin][j] = dp[1 - lin][j];

      if (j + e[i] >= target) {
        sol = std::min(sol, dp[lin][j] + c[i]);
      }

      if (j >= e[i])
        dp[lin][j] = std::min(dp[lin][j], dp[1 - lin][j - e[i]] + c[i]);
    }
  }

  out << sol;

  out.close();
  return 0;
}