QUBO++ Library with QUBO Solver APIs
Author: Koji Nakano, License: Non-commercial research and evaluation purposes without any guarantees.
knapsack_exhaustive.cpp
Go to the documentation of this file.
1 
8 #include "qbpp.hpp"
10 
11 int main() {
12  // The values and weights of items.
13  qbpp::Vector<int> values = {20, 30, 50, 60, 40, 10, 25, 35};
14  qbpp::Vector<int> weights = {4, 5, 8, 7, 6, 3, 4, 5};
15 
16  // Define a vector of binary variables.
17  // x[i] = 1 if item i is selected, 0 otherwise.
18  auto x = qbpp::var("x", values.size());
19 
20  // Define the objective function, which is to maximize the total value of
21  // selected items.
22  auto objective = qbpp::sum(x * values);
23 
24  // Define the constraint, which is to limit the total weight of selected items
25  // to at most 20.
26  auto constraint = 0 <= qbpp::sum(x * weights) <= 20;
27 
28  // Define the QUBO expression.
29  auto f = -objective + constraint * 1000;
30 
32 
33  std::cout << "f = " << f << std::endl;
34 
36 
37  auto sol = solver.search();
38 
39  std::cout << "Solution = " << sol << std::endl;
40 
41  for (size_t i = 0; i < values.size(); i++) {
42  if (sol.get(x[i]) == 1) {
43  std::cout << "Item " << i << " with value " << values[i] << " and weight "
44  << weights[i] << " is selected" << std::endl;
45  }
46  }
47 }
Expr & simplify_as_binary()
Definition: qbpp.hpp:1956
size_t size() const
Definition: qbpp.hpp:385
int main()
Var var(const std::string &var_str)
Definition: qbpp.hpp:2172
Expr sum(const Vector< T > &items)
Definition: qbpp.hpp:3209
QUBO++, a C++ library for generating expressions for binary and spin variables.
Exhaustive QUBO Solver for solving QUBO problems.