1 #include <ilcplex/ilocplex.h>
2 #include<cstdlib>
3 #include<iostream>
4
5
6
7 // maximize x1+2x2+3x3;
8
9 // subject to{
10 // (-x1)+x2+x3<=20;
11 // x1-(3x2)+x3<=30;
12 // }
13
14 // Bounds{
15 // 0<=x1<=40;
16 // 0<=x2<=inf;
17 // 0<=x3<=inf;
18 // }
19
20
21 ILOSTLBEGIN //#define ILOSTLBEGIN using namespace std;
22
23 int
24 main(int argc, char **argv)
25 {
26 IloEnv env;//construct an Cplex environment env, which belongs to a handle class
IloEnv;
27
28 try {
29 IloModel model(env);// define the varies "env"
30 IloNumVarArray vars(env);// define the varies vars(env), the x1, x2, x3 can
be expressed with vars(0), vars(1), vars(2)
31 // define the bounds of varies
32 vars.add(IloNumVar(env, 0.0, 40.0));
33 vars.add(IloNumVar(env));
34 vars.add(IloNumVar(env));
35
36 //objective to optimize:
37 model.add(IloMaximize(env, vars[0] + 2 * vars[1] + 3 *
vars[2]));//opjective: Maximize the x1+2*x2+3*x3;
38
39 //subject to:
40 model.add(-vars[0] + vars[1] + vars[2] <= 20);
41 model.add(vars[0] - 3 * vars[1] + vars[2] <= 30);
42
43 //expection processing, refer to "C++ try&catch"
44 IloCplex cplex(model);
45 if (!cplex.solve()) {
46 env.error() << "Failed to optimize LP." << endl;
47 throw(-1);
48 }
49
50 IloNumArray vals(env);
51 env.out() << "solution status = " << cplex.getStatus() << endl;
52 env.out() << "Solution value=" << cplex.getObjective() << endl;
53 cplex.getValues(vals, vars);
54 env.out() << "Values = " << vals << endl;
55 }
56
57 // cathch functions, refer to "C++ try&catch"
58 catch (IloException&e) {
59 cerr << "Concert exception caught:" << e << endl;
60 }
61 catch (...) {
62 cerr << "Unknown exception caught" << endl;
63 }
64
65 env.end();
66 //return 0;
67 system("PAUSE");
68 return EXIT_SUCCESS;
69 }
评论1