Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
size_t CalcScore(const Problem& p, const std::vector<size_t>& order) {
MPSolver solver("solving_all_cases",
MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING);
std::vector<MPVariable*> books_vars;
std::vector<std::vector<MPVariable*>> libraries_vars;
const double infinity = solver.infinity();
for (size_t i = 0; i < p.books_num; ++i) {
books_vars.push_back(solver.MakeBoolVar(absl::StrCat("x_", i)));
}
for (const size_t ind : order) {
auto& back = libraries_vars.emplace_back();
for (size_t i = 0; i < p.libraries[ind].books_indices.size(); ++i) {
back.push_back(solver.MakeBoolVar(absl::StrCat("y_", i, ind)));
}
}
size_t day = 0;
size_t iter = 0;
for (const size_t ind : order) {
day += p.libraries[ind].install_time;
MPConstraint* const libs_c = solver.MakeRowConstraint(-infinity, (p.days - day) * p.libraries[ind].day_capacity);
for (size_t i = 0; i < p.libraries[ind].books_indices.size(); ++i) {
libs_c->SetCoefficient(libraries_vars[iter][i], 1.0);
}
++iter;
}
std::vector<MPConstraint*> last_c;
for (size_t i = 0; i < p.books_num; ++i) {
last_c.push_back(solver.MakeRowConstraint(-infinity, 0));
last_c.back()->SetCoefficient(books_vars[i], 1.0);
}
iter = 0;
for (const size_t ind : order) {
for (size_t i = 0; i < p.libraries[ind].books_indices.size(); ++i) {
last_c[p.libraries[ind].books_indices[i]]->SetCoefficient(libraries_vars[iter][i], -1.0);
}
++iter;
}
MPObjective* const objective = solver.MutableObjective();
for (size_t i = 0; i < p.books_num; ++i) {
objective->SetCoefficient(books_vars[i], 1.0 * p.books[i]);
}
objective->SetMaximization();
solver.SetTimeLimit(absl::Seconds(120));
auto start = absl::Now();
const MPSolver::ResultStatus result_status = solver.Solve();
auto finish = absl::Now();
std::cerr << "Processed " << finish - start << std::endl;
if (result_status != MPSolver::OPTIMAL) {
std::cerr << "The problem does not have an optimal solution!" << std::endl;
}
std::vector<std::vector<bool>> mask;
iter = 0;
for (const size_t ind : order) {
auto& back = mask.emplace_back();
for (size_t i = 0; i < p.libraries[ind].books_indices.size(); ++i) {
back.push_back(libraries_vars[iter][i]->solution_value() == 1.0);
}
++iter;
}
std::cerr << "Expected objective: " << static_cast<size_t>(objective->Value()) << std::endl;
auto got = CalcScore(p, order, mask, print_out);
std::cerr << "Got: " << got << std::endl;
return got;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.