首页 > 解决方案 > CPLEX C++:避免​​将变量添加到两个变量数组中

问题描述

我有两个IloNumVarArrays,叫做pp_old。我想保存当前状态p_old并向其中添加新变量p(但只是p因为p_old应该是备份)。但是当我向 中添加新变量p并将它们添加到我的模型时,它们也会被添加到p_old。我想避免将它们添加p_oldp_old. 这是一个例子。

#include <vector>
#include <ilcplex/ilocplex.h>
ILOSTLBEGIN

int main(){
  
  bool solved;

  // vector R contains all requests
  std::vector <int> R = {0,1,2,3,4,5,6,7,8,9,10};

  int new_request;
  
  // use this stringstream to create variable and constraint names
  std::stringstream name;

  IloEnv             env;
  IloModel     model(env);
  IloNumVarArray p(env,R.size());
  IloConstraintArray accept(env,R.size());
  IloNumVarArray p_old(env, R.size());
  for (const auto& i: R)
  {
    name << "p_" << i;
    p[i] = IloNumVar(env, 0, 1, ILOBOOL, name.str().c_str()); 
    name.str("");
    p_old[i] = p[i];
  }


  
  IloExpr expr(env);
  // Create objective function
  for (const auto& i : R)
  {
      expr += p[i]; 
  }
  IloObjective obj(env, expr, IloObjective::Minimize);
  model.add(obj);
  expr.clear();
  
  env.out() << endl << p << endl;
  env.out() << endl << p_old << endl;
  // Create the solver object
  IloCplex cplex(model);
  env.out() << "Before" << endl;
  env.out() << model << endl;
  cplex.exportModel("Before.lp");
  
  solved = cplex.solve();
  if (solved)
  {
    // If CPLEX successfully solved the model, print the results
    std::cout << "\n\nCplex success!\n";
    std::cout << "\tStatus: " << cplex.getStatus() << "\n";
    std::cout << "\tObjective value: " << cplex.getObjValue() << "\n";

    // remove p_1 and p_2 from model
    p[1].end();
    p[2].end();
    
    // add new request to R, create variable p and corresponding constraint
    new_request = 11;
    R.push_back(new_request);
    name << "p_" << new_request;
    p.add(IloNumVar(env,0,1,ILOBOOL,name.str().c_str()));
    name.str("");

    
    new_request = 12;
    R.push_back(new_request);
    name << "p_" << new_request;
    p.add(IloNumVar(env,0,1,ILOBOOL,name.str().c_str()));
    name.str("");

    accept.add(2, IloRange());
    accept[11] = IloRange(env,1,p[11],1,"accept_11");
    accept[12] = IloRange(env,1,p[12],1,"accept_12");
    model.add(accept[11]);
    model.add(accept[12]);

    env.out() << endl << p << endl;
    env.out() << endl << p_old << endl;

    env.out() << "After" << endl;
    env.out() << model << endl;
    cplex.exportModel("After.lp");
    solved = cplex.solve();
  }
  
  expr.end();
  env.end();
}

整个事情背后的原因是我有一个更大的拨号问题模型,它接收新请求并在每次新请求到达时解决。当发生这种情况时,将添加与新请求相对应的变量和约束。但是,添加所有这些变量和约束可能需要不超过 10 秒的时间,因为请求必须快速收到答复。如果碰巧在 10 秒后修改模型还没有完成,则请求被拒绝,即不再需要之前添加的所有变量和约束,并且我不想将它们包含在模型中。那就是我需要的地方IloNumVarArray p_old,因此在超时修改后,我可以使用

p.end_elements();
p.add(p_old.getSize(), IloNumVar());
for (const auto& i: R)
{
    p[i] = p_old[i];
}

或类似的东西......有人有什么想法吗?非常感谢您的帮助!

标签: c++cplex

解决方案


推荐阅读