1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package org.sat4j.opt;
26
27 import org.sat4j.core.VecInt;
28 import org.sat4j.specs.ContradictionException;
29 import org.sat4j.specs.IOptimizationProblem;
30 import org.sat4j.specs.ISolver;
31 import org.sat4j.specs.IVecInt;
32 import org.sat4j.specs.TimeoutException;
33 import org.sat4j.tools.SolverDecorator;
34
35
36
37
38
39
40
41
42 public class MinOneDecorator extends SolverDecorator implements
43 IOptimizationProblem {
44
45
46
47
48 private static final long serialVersionUID = 1L;
49
50 private int[] prevmodel;
51
52 public MinOneDecorator(ISolver solver) {
53 super(solver);
54 }
55
56 public boolean admitABetterSolution() throws TimeoutException {
57 boolean result = isSatisfiable();
58 if (result) {
59 prevmodel = super.model();
60 }
61 return result;
62 }
63
64 public boolean hasNoObjectiveFunction() {
65 return false;
66 }
67
68 public boolean nonOptimalMeansSatisfiable() {
69 return true;
70 }
71
72 private int counter;
73
74 public Number calculateObjective() {
75 counter = 0;
76 for (int p : prevmodel) {
77 if (p > 0) {
78 counter++;
79 }
80 }
81 return counter;
82 }
83
84 private final IVecInt literals = new VecInt();
85
86 public void discard() throws ContradictionException {
87 if (literals.isEmpty()) {
88 for (int i = 1; i <= nVars(); i++) {
89 literals.push(i);
90 }
91 }
92 addAtMost(literals, counter - 1);
93 }
94
95 @Override
96 public int[] model() {
97
98 return prevmodel;
99 }
100
101 @Override
102 public void reset() {
103 literals.clear();
104 super.reset();
105 }
106
107 }