Generated on Sat Feb 7 2015 02:01:12 for Gecode by doxygen 1.8.9.1
queen-armies.cpp
Go to the documentation of this file.
1 /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
2 /*
3  * Main authors:
4  * Mikael Lagerkvist <lagerkvist@gecode.org>
5  *
6  * Copyright:
7  * Mikael Lagerkvist, 2006
8  *
9  * Last modified:
10  * $Date: 2013-07-08 14:22:40 +0200 (Mon, 08 Jul 2013) $ by $Author: schulte $
11  * $Revision: 13820 $
12  *
13  * This file is part of Gecode, the generic constraint
14  * development environment:
15  * http://www.gecode.org
16  *
17  * Permission is hereby granted, free of charge, to any person obtaining
18  * a copy of this software and associated documentation files (the
19  * "Software"), to deal in the Software without restriction, including
20  * without limitation the rights to use, copy, modify, merge, publish,
21  * distribute, sublicense, and/or sell copies of the Software, and to
22  * permit persons to whom the Software is furnished to do so, subject to
23  * the following conditions:
24  *
25  * The above copyright notice and this permission notice shall be
26  * included in all copies or substantial portions of the Software.
27  *
28  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
29  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
31  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
32  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
33  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
34  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35  *
36  */
37 
38 
39 #include <gecode/driver.hh>
40 #include <gecode/int.hh>
41 #include <gecode/minimodel.hh>
42 #include <gecode/set.hh>
43 
44 using namespace Gecode;
45 
51 
72 public:
73  const int n;
74  SetVar U,
75  W;
77  b;
79 
81  enum {
83  BRANCH_SPECIFIC
84  };
85 
88  n(opt.size()),
89  U(*this, IntSet::empty, IntSet(0, n*n)),
90  W(*this, IntSet::empty, IntSet(0, n*n)),
91  w(*this, n*n, 0, 1),
92  b(*this, n*n, 0, 1),
93  q(*this, 0, n*n)
94  {
95  // Basic rules of the model
96  for (int i = n*n; i--; ) {
97  // w[i] means that no blacks are allowed on A[i]
98  rel(*this, w[i] == (U || A[i]));
99  // Make sure blacks and whites are disjoint.
100  rel(*this, !w[i] || !b[i]);
101  // If i in U, then b[i] has a piece.
102  rel(*this, b[i] == (singleton(i) <= U));
103  }
104 
105  // Connect optimization variable to number of pieces
106  linear(*this, w, IRT_EQ, q);
107  linear(*this, b, IRT_GQ, q);
108 
109  // Connect cardinality of U to the number of black pieces.
110  IntVar unknowns = expr(*this, cardinality(U));
111  rel(*this, q <= unknowns);
112  linear(*this, b, IRT_EQ, unknowns);
113 
114  if (opt.branching() == BRANCH_NAIVE) {
115  branch(*this, w, INT_VAR_NONE(), INT_VAL_MAX());
116  branch(*this, b, INT_VAR_NONE(), INT_VAL_MAX());
117  } else {
118  QueenBranch::post(*this);
119  assign(*this, b, INT_ASSIGN_MAX());
120  }
121  }
123  QueenArmies(bool share, QueenArmies& s)
124  : IntMaximizeScript(share,s), n(s.n) {
125  U.update(*this, share, s.U);
126  W.update(*this, share, s.W);
127  w.update(*this, share, s.w);
128  b.update(*this, share, s.b);
129  q.update(*this, share, s.q);
130  }
132  virtual Space*
133  copy(bool share) {
134  return new QueenArmies(share,*this);
135  }
137  virtual IntVar cost(void) const {
138  return q;
139  }
141  virtual void
142  print(std::ostream& os) const {
143  os << '\t';
144  for (int i = 0; i < n*n; ++i) {
145  if (w[i].assigned() && w[i].val()) os << "W";
146  else if (b[i].assigned() && b[i].val()) os << "B";
147  else if (!w[i].assigned() && !b[i].assigned()) os << " ";
148  else os << ".";
149  if ((i+1)%n == 0) os << std::endl << (i!=(n*n-1)?"\t":"");
150  }
151  os << "Number of white queens: " << q << std::endl << std::endl;
152  }
153 
161  class QueenBranch : public Brancher {
162  private:
164  mutable int start;
166  class Choice : public Gecode::Choice {
167  public:
169  int pos;
171  bool val;
175  Choice(const Brancher& b, int pos0, bool val0)
176  : Gecode::Choice(b,2), pos(pos0), val(val0) {}
178  virtual size_t size(void) const {
179  return sizeof(Choice);
180  }
182  virtual void archive(Archive& e) const {
184  e << pos << val;
185  }
186  };
187 
189  QueenBranch(Home home)
190  : Brancher(home), start(0) {}
192  QueenBranch(Space& home, bool share, QueenBranch& b)
193  : Brancher(home, share, b), start(b.start) {}
194 
195  public:
197  virtual bool status(const Space& home) const {
198  const QueenArmies& q = static_cast<const QueenArmies&>(home);
199  for (int i = start; i < q.n*q.n; ++i)
200  if (!q.w[i].assigned()) {
201  start = i;
202  return true;
203  }
204  // No non-assigned orders left
205  return false;
206  }
208  virtual Gecode::Choice* choice(Space& home) {
209  const QueenArmies& q = static_cast<const QueenArmies&>(home);
210  int maxsize = -1;
211  int pos = -1;
212 
213  for (int i = start; i < q.n*q.n; ++i) {
214  if (q.w[i].assigned()) continue;
215  IntSetRanges ai(A[i]);
216  SetVarUnknownRanges qU(q.U);
218  int size = Iter::Ranges::size(r);
219  if (size > maxsize) {
220  maxsize = size;
221  pos = i;
222  }
223  }
224 
225  assert(pos != -1);
226  return new Choice(*this, pos, true);
227  }
229  virtual Choice* choice(const Space&, Archive& e) {
230  int pos, val;
231  e >> pos >> val;
232  return new Choice(*this, pos, val);
233  }
237  virtual ExecStatus commit(Space& home, const Gecode::Choice& _c,
238  unsigned int a) {
239  QueenArmies& q = static_cast<QueenArmies&>(home);
240  const Choice& c = static_cast<const Choice&>(_c);
241  bool val = (a == 0) ? c.val : !c.val;
242  return me_failed(Int::BoolView(q.w[c.pos]).eq(q, val))
243  ? ES_FAILED
244  : ES_OK;
245  }
247  virtual void print(const Space&, const Gecode::Choice& _c,
248  unsigned int a,
249  std::ostream& o) const {
250  const Choice& c = static_cast<const Choice&>(_c);
251  bool val = (a == 0) ? c.val : !c.val;
252  o << "w[" << c.pos << "] = " << val;
253  }
255  virtual Actor* copy(Space& home, bool share) {
256  return new (home) QueenBranch(home, share, *this);
257  }
260  return *new (home) QueenBranch(home);
261  }
263  virtual size_t dispose(Space&) {
264  return sizeof(*this);
265  }
266  };
267 };
268 
273 int pos(int i, int j, int n) {
274  return i*n + j;
275 }
276 
280 int
281 main(int argc, char* argv[]) {
282  SizeOptions opt("QueenArmies");
283  opt.size(6);
285  opt.branching(QueenArmies::BRANCH_NAIVE, "naive");
286  opt.branching(QueenArmies::BRANCH_SPECIFIC, "specific");
287  opt.solutions(0);
288  opt.parse(argc,argv);
289 
290  // Set up the A-sets
291  // A[i] will contain the values attacked by a queen at position i
292  int n = opt.size();
293  A = new IntSet[n*n];
294  int *p = new int[std::max(n*n, 25)];
295  int pn = 0;
296  for (int i = n; i--; ) {
297  for (int j = n; j--; ) {
298  int dir[][2] = {
299  { 0, 1},
300  { 1, 1},
301  { 1, 0},
302  { 0, -1},
303  {-1, -1},
304  {-1, 0},
305  { 1, -1},
306  {-1, 1}
307  };
308  p[pn++] = pos(i, j, n);
309  for (int k = 8; k--; ) {
310  for (int l = 0; l < n
311  && 0 <= (i+l*dir[k][0]) && (i+l*dir[k][0]) < n
312  && 0 <= (j+l*dir[k][1]) && (j+l*dir[k][1]) < n; ++l) {
313  p[pn++] = pos(i+l*dir[k][0], j+l*dir[k][1], n);
314  }
315  }
316 
317  A[pos(i, j, n)] = IntSet(p, pn);
318 
319  pn = 0;
320  }
321  }
322  delete [] p;
323 
324  IntMaximizeScript::run<QueenArmies,BAB,SizeOptions>(opt);
325  return 0;
326 }
327 
328 // STATISTICS: example-any
virtual Gecode::Choice * choice(Space &home)
Return choice.
void size(unsigned int s)
Set default size.
Definition: options.hpp:467
SetExpr singleton(const LinIntExpr &e)
Singleton expression.
Definition: set-expr.cpp:691
Options for scripts with additional size parameter
Definition: driver.hh:567
Choose variables left to right.
virtual void print(const Space &, const Gecode::Choice &_c, unsigned int a, std::ostream &o) const
Print explanation.
IntVarBranch INT_VAR_NONE(void)
Select first unassigned variable.
Definition: var.hpp:108
void linear(Home home, const FloatVarArgs &x, FloatRelType frt, FloatNum c)
Post propagator for .
Definition: linear.cpp:45
NNF * l
Left subtree.
Definition: bool-expr.cpp:244
void post(Home home, Term *t, int n, FloatRelType frt, FloatVal c)
Post propagator for linear constraint over floats.
Definition: post.cpp:228
Range iterator for integer sets.
Definition: int.hh:271
const FloatNum max
Largest allowed float value.
Definition: float.hh:831
virtual Choice * choice(const Space &, Archive &e)
Return choice.
IntVar q
The number of white queens placed.
void update(Space &home, bool share, VarImpVar< VarImp > &y)
Update this variable to be a clone of variable y.
Definition: var.hpp:128
int main(int argc, char *argv[])
Main-function.
SetVar W
Set of squares occupied by white queens.
void parse(int &argc, char *argv[])
Parse options from arguments argv (number is argc)
Definition: options.cpp:435
Handle for brancher.
Definition: core.hpp:1157
bool pos(const View &x)
Test whether x is postive.
Definition: mult.hpp:45
virtual ExecStatus commit(Space &home, const Gecode::Choice &_c, unsigned int a)
Perform commit for choice _c and alternative a.
QueenArmies(bool share, QueenArmies &s)
Constructor for cloning.
virtual Space * copy(bool share)
Return copy during cloning.
int pos(int i, int j, int n)
Position of a piece in a square board.
BoolVarArray w
The placement of the white queens.
QueenArmies(const SizeOptions &opt)
Constructor.
Computation spaces.
Definition: core.hpp:1362
Greater or equal ( )
Definition: int.hh:908
Parametric base-class for scripts.
Definition: driver.hh:622
Base-class for both propagators and branchers.
Definition: core.hpp:666
static BrancherHandle post(QueenArmies &home)
Post brancher.
ModEvent eq(Space &home, int n)
Restrict domain values to be equal to n.
Definition: bool.hpp:164
Iterator for the unknown ranges of a set variable.
Definition: set.hh:336
virtual size_t dispose(Space &)
Delete brancher and return its size.
void update(Space &, bool share, VarArray< Var > &a)
Update array to be a clone of array a.
Definition: array.hpp:1072
Gecode::FloatVal c(-8, 8)
int p
Number of positive literals for node type.
Definition: bool-expr.cpp:236
Gecode::IntArgs i(4, 1, 2, 3, 4)
Base-class for branchers.
Definition: core.hpp:1071
int n
Number of negative literals for node type.
Definition: bool-expr.cpp:238
Equality ( )
Definition: int.hh:904
Options opt
The options.
Definition: test.cpp:101
Execution has resulted in failure.
Definition: core.hpp:525
Example: Peaceable co-existing armies of queens
Range iterator for computing intersection (binary)
NNF * r
Right subtree.
Definition: bool-expr.cpp:246
IntAssign INT_ASSIGN_MAX(void)
Select largest value.
Definition: assign.hpp:69
IntSet * A
Position of a piece in a square board.
virtual void archive(Archive &e) const
Archive into e.
Definition: core.cpp:670
unsigned int size(I &i)
Size of all ranges of range iterator i.
const int n
Integer sets.
Definition: int.hh:171
void branching(int v)
Set default branching value.
Definition: options.hpp:203
virtual Actor * copy(Space &home, bool share)
Copy brancher during cloning.
SetVar U
Set of un-attacked squares.
Boolean variable array.
Definition: int.hh:786
LinIntExpr cardinality(const SetExpr &e)
Cardinality of set expression.
Definition: set-expr.cpp:815
IntValBranch INT_VAL_MAX(void)
Select largest value.
Definition: val.hpp:78
BoolVar expr(Home home, const BoolExpr &e, IntConLevel icl)
Post Boolean expression and return its value.
Definition: bool-expr.cpp:632
BrancherHandle assign(Home home, const FloatVarArgs &x, FloatAssign fa, FloatBranchFilter bf, FloatVarValPrint vvp)
Assign all x with value selection vals.
Definition: branch.cpp:113
Set variables
Definition: set.hh:129
Choice for performing commit
Definition: core.hpp:1036
virtual void print(std::ostream &os) const
Print solution.
Archive representation
Definition: archive.hpp:45
ExecStatus
Definition: core.hpp:523
BoolVarArray b
The placement of the black queens.
Integer variables.
Definition: int.hh:350
bool assigned(View x, int v)
Whether x is assigned to value v.
Definition: single.hpp:47
void rel(Home home, FloatVar x0, FloatRelType frt, FloatVal n)
Propagates .
Definition: rel.cpp:47
void solutions(unsigned int n)
Set default number of solutions to search for.
Definition: options.hpp:243
Execution is okay.
Definition: core.hpp:527
Custom brancher for Peacable queens.
Choose variable with problem specific strategy.
struct Gecode::@518::NNF::@57::@58 b
For binary nodes (and, or, eqv)
Gecode toplevel namespace
virtual bool status(const Space &home) const
Check status of brancher, return true if alternatives left.
bool assigned(void) const
Test if all variables are assigned.
Definition: array.hpp:1085
BrancherHandle branch(Home home, const FloatVarArgs &x, FloatVarBranch vars, FloatValBranch vals, FloatBranchFilter bf, FloatVarValPrint vvp)
Branch over x with variable selection vars and value selection vals.
Definition: branch.cpp:43
Home class for posting propagators
Definition: core.hpp:717
virtual IntVar cost(void) const
Return solution cost.
struct Gecode::@518::NNF::@57::@59 a
For atomic nodes.
bool me_failed(ModEvent me)
Check whether modification event me is failed.
Definition: modevent.hpp:58
Multi _c(Gecode::IntArgs(3, 1, 2, 3))
Boolean view for Boolean variables.
Definition: view.hpp:1315