Cod sursa(job #2199891)

Utilizator georgeromanGeorge Roman georgeroman Data 29 aprilie 2018 15:09:10
Problema Energii Scor 95
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.11 kb
#include <algorithm>
#include <fstream>
#include <utility>
#include <vector>

#define INF 0x3f3f3f3f

int main() {
  std::ifstream in("energii.in");
  std::ofstream out("energii.out");

  unsigned g, w;
  in >> g >> w;
  std::vector<std::pair<long, long>> generators;
  generators.reserve(g);
  for (unsigned i = 0; i < g; i++) {
    long energy, cost;
    in >> energy >> cost;
    generators.push_back(std::make_pair(energy, cost));
  }

  std::vector<std::vector<long>> dp;
  dp.reserve(g + 1);
  for (unsigned i = 0; i <= g; i++) {
    dp.push_back(std::vector<long>());
    dp[i].reserve(w);
    for (unsigned j = 0; j < w; j++) {
      dp[i].push_back(INF);
    }
  }

  for (unsigned i = 1; i <= g; i++) {
    for (unsigned j = 0; j < w; j++) {
      long previousMax = dp[i - 1][j];
      long currentCost = generators[i - 1].second;
      long subEnergy = j + 1 - generators[i - 1].first;
      long subCost = subEnergy <= 0 ? 0 : dp[i - 1][subEnergy];
      dp[i][j] = std::min(previousMax, currentCost + subCost);
    }
  }

  if (dp[g][w - 1] == INF) out << -1 << "\n";
  else out << dp[g][w - 1] << "\n";

  return 0;
}