Bläddra i källkod

20170412 para with aspiration

Sandy Cheung 8 år sedan
incheckning
11f3a3d2dd

+ 15 - 0
README

@@ -0,0 +1,15 @@
+to compile: 
+make 
+This will create an executable in bin directory.
+
+to clean: 
+make clean
+
+to run: 
+./shell ReasonLS-run.sh $1 $2 
+
+
+$1   :inputFile  absolutely path
+
+$2   :-drup-file=$2/proof.out 
+

+ 4 - 0
ReasonLS-run.sh

@@ -0,0 +1,4 @@
+#! /bin/bash
+
+cd bin
+python ./pmaple.py $1 6 14 -drup-file=$2/proof.out

+ 4 - 0
makefile

@@ -0,0 +1,4 @@
+all:
+	cd sources/simp;make rs; cp ReasonLS_static ../../bin/ReasonLS; cp pmaple.py ../../bin/pmaple.py
+clean:
+	cd sources/simp;make clean;cd ../../bin;rm ReasonLS pmaple.py

BIN
sources/.DS_Store


BIN
sources/core/.DS_Store


+ 157 - 0
sources/core/Dimacs.h

@@ -0,0 +1,157 @@
+/****************************************************************************************[Dimacs.h]
+Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2007-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_Dimacs_h
+#define Minisat_Dimacs_h
+
+#include <stdio.h>
+
+#include "utils/ParseUtils.h"
+#include "core/SolverTypes.h"
+
+namespace Minisat {
+
+//=================================================================================================
+// DIMACS Parser:
+
+template<class B, class Solver>
+static void readClause(B& in, Solver& S, vec<Lit>& lits) {
+    int     parsed_lit, var;
+    lits.clear();
+    for (;;){
+        parsed_lit = parseInt(in);
+        if (parsed_lit == 0) break;
+        var = abs(parsed_lit)-1;
+        while (var >= S.nVars()) S.newVar();
+        lits.push( (parsed_lit > 0) ? mkLit(var) : ~mkLit(var) );
+    }
+}
+
+template<class B, class Solver>
+static void parse_DIMACS_main(B& in, Solver& S) {
+    vec<Lit> lits;
+    int vars    = 0;
+    int clauses = 0;
+    int cnt     = 0;
+    for (;;){
+        skipWhitespace(in);
+        if (*in == EOF) break;
+        else if (*in == 'p'){
+            if (eagerMatch(in, "p cnf")){
+                vars    = parseInt(in);
+                clauses = parseInt(in);
+                // SATRACE'06 hack
+                // if (clauses > 4000000)
+                //     S.eliminate(true);
+            }else{
+                printf("PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
+            }
+        } else if (*in == 'c' || *in == 'p')
+            skipLine(in);
+        else{
+            cnt++;
+            readClause(in, S, lits);
+            S.addClause_(lits); }
+    }
+    if (vars != S.nVars())
+        fprintf(stderr, "WARNING! DIMACS header mismatch: wrong number of variables.\n");
+    if (cnt  != clauses)
+        fprintf(stderr, "WARNING! DIMACS header mismatch: wrong number of clauses.\n");
+}
+
+// Inserts problem into solver.
+//
+template<class Solver>
+static void parse_DIMACS(gzFile input_stream, Solver& S) {
+    StreamBuffer in(input_stream);
+    parse_DIMACS_main(in, S); }
+
+//=================================================================================================
+
+template<class B, class Solver>
+static void simple_readClause(B& in, Solver& S, vec<Lit>& lits) {
+    int     parsed_lit, var;
+    lits.clear();
+    for (;;){
+        parsed_lit = parseInt(in);
+        if (parsed_lit == 0) break;
+        var = abs(parsed_lit)-1;
+        lits.push( (parsed_lit > 0) ? mkLit(var) : ~mkLit(var) );
+    }
+}
+
+template<class B, class Solver>
+static void check_solution_DIMACS_main(B& in, Solver& S) {
+    vec<Lit> lits;
+    int vars    = 0;
+    int clauses = 0;
+    int cnt     = 0;
+    bool ok=true;
+    for (;;){
+        skipWhitespace(in);
+        if (*in == EOF) break;
+        else if (*in == 'p'){
+            if (eagerMatch(in, "p cnf")){
+                vars    = parseInt(in);
+                clauses = parseInt(in);
+                // SATRACE'06 hack
+                // if (clauses > 4000000)
+                //     S.eliminate(true);
+            }else{
+                printf("c PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
+            }
+        } else if (*in == 'c' || *in == 'p')
+            skipLine(in);
+        else{
+            cnt++;
+            int parsed_lit, var;
+            bool ok=false;
+            for(;;) {
+                parsed_lit = parseInt(in);
+                if (parsed_lit == 0) break; //{printf("\n"); break;}
+                var = abs(parsed_lit)-1;
+                // printf("%d ", parsed_lit);
+                if ((parsed_lit>0 && S.model[var]==l_True) ||
+                        (parsed_lit<0 && S.model[var]==l_False))
+                    ok=true;
+            }
+            if (!ok) {
+                printf("c clause %d is not satisfied\n", cnt);
+                ok=false;
+                // break;
+            }
+        }
+    }
+    if (cnt  != clauses)
+        printf("c WARNING! DIMACS header mismatch: wrong number of clauses.%d %d\n", cnt, clauses);
+    else if (ok)
+        printf("c solution checked against the original DIMACS file\n");
+}
+
+template<class Solver>
+static void check_solution_DIMACS(gzFile input_stream, Solver& S) {
+    StreamBuffer in(input_stream);
+    check_solution_DIMACS_main(in, S); }
+
+//=================================================================================================
+}
+
+#endif
+

+ 214 - 0
sources/core/Main.cc

@@ -0,0 +1,214 @@
+/*****************************************************************************************[Main.cc]
+Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2007-2010, Niklas Sorensson
+ 
+Chanseok Oh's MiniSat Patch Series -- Copyright (c) 2015, Chanseok Oh
+
+Maple_LCM, Based on MapleCOMSPS_DRUP -- Copyright (c) 2017, Mao Luo, Chu-Min LI, Fan Xiao: implementing a learnt clause minimisation approach
+Reference: M. Luo, C.-M. Li, F. Xiao, F. Manya, and Z. L. , “An effective learnt clause minimization approach for cdcl sat solvers,” in IJCAI-2017, 2017, pp. to–appear.
+ 
+Maple_LCM_Dist, Based on Maple_LCM -- Copyright (c) 2017, Fan Xiao, Chu-Min LI, Mao Luo: using a new branching heuristic called Distance at the beginning of search
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#include <errno.h>
+
+#include <signal.h>
+#include <zlib.h>
+
+#include "utils/System.h"
+#include "utils/ParseUtils.h"
+#include "utils/Options.h"
+#include "core/Dimacs.h"
+#include "core/Solver.h"
+
+using namespace Minisat;
+
+//=================================================================================================
+
+
+void printStats(Solver& solver)
+{
+    double cpu_time = cpuTime();
+    double mem_used = memUsedPeak();
+    printf("c restarts              : %"PRIu64"\n", solver.starts);
+    printf("c conflicts             : %-12"PRIu64"   (%.0f /sec)\n", solver.conflicts   , solver.conflicts   /cpu_time);
+    printf("c decisions             : %-12"PRIu64"   (%4.2f %% random) (%.0f /sec)\n", solver.decisions, (float)solver.rnd_decisions*100 / (float)solver.decisions, solver.decisions   /cpu_time);
+    printf("c propagations          : %-12"PRIu64"   (%.0f /sec)\n", solver.propagations, solver.propagations/cpu_time);
+    printf("c conflict literals     : %-12"PRIu64"   (%4.2f %% deleted)\n", solver.tot_literals, (solver.max_literals - solver.tot_literals)*100 / (double)solver.max_literals);
+    if (mem_used != 0) printf("c Memory used           : %.2f MB\n", mem_used);
+    printf("c CPU time              : %g s\n", cpu_time);
+}
+
+
+static Solver* solver;
+// Terminate by notifying the solver and back out gracefully. This is mainly to have a test-case
+// for this feature of the Solver as it may take longer than an immediate call to '_exit()'.
+static void SIGINT_interrupt(int signum) { solver->interrupt(); }
+
+// Note that '_exit()' rather than 'exit()' has to be used. The reason is that 'exit()' calls
+// destructors and may cause deadlocks if a malloc/free function happens to be running (these
+// functions are guarded by locks for multithreaded use).
+static void SIGINT_exit(int signum) {
+    printf("\n"); printf("c *** INTERRUPTED ***\n");
+    if (solver->verbosity > 0){
+        printStats(*solver);
+        printf("\n"); printf("c *** INTERRUPTED ***\n"); }
+    _exit(1); }
+
+
+//=================================================================================================
+// Main:
+
+
+int main(int argc, char** argv)
+{
+    try {
+        setUsageHelp("USAGE: %s [options] <input-file> <result-output-file>\n\n  where input may be either in plain or gzipped DIMACS.\n");
+        printf("c This is COMiniSatPS.\n");
+        
+#if defined(__linux__)
+        fpu_control_t oldcw, newcw;
+        _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw);
+        printf("c WARNING: for repeatability, setting FPU to use double precision\n");
+#endif
+        // Extra options:
+        //
+        IntOption    verb   ("MAIN", "verb",   "Verbosity level (0=silent, 1=some, 2=more).", 1, IntRange(0, 2));
+        IntOption    cpu_lim("MAIN", "cpu-lim","Limit on CPU time allowed in seconds.\n", INT32_MAX, IntRange(0, INT32_MAX));
+        IntOption    mem_lim("MAIN", "mem-lim","Limit on memory usage in megabytes.\n", INT32_MAX, IntRange(0, INT32_MAX));
+        
+        parseOptions(argc, argv, true);
+
+        Solver S;
+        double initial_time = cpuTime();
+        //-------------------
+        //==================
+        S.verbosity = verb;
+        
+        solver = &S;
+        // Use signal handlers that forcibly quit until the solver will be able to respond to
+        // interrupts:
+        signal(SIGINT, SIGINT_exit);
+        signal(SIGXCPU,SIGINT_exit);
+
+        // Set limit on CPU-time:
+        if (cpu_lim != INT32_MAX){
+            rlimit rl;
+            getrlimit(RLIMIT_CPU, &rl);
+            if (rl.rlim_max == RLIM_INFINITY || (rlim_t)cpu_lim < rl.rlim_max){
+                rl.rlim_cur = cpu_lim;
+                if (setrlimit(RLIMIT_CPU, &rl) == -1)
+                    printf("c WARNING! Could not set resource limit: CPU-time.\n");
+            } }
+
+        // Set limit on virtual memory:
+        if (mem_lim != INT32_MAX){
+            rlim_t new_mem_lim = (rlim_t)mem_lim * 1024*1024;
+            rlimit rl;
+            getrlimit(RLIMIT_AS, &rl);
+            if (rl.rlim_max == RLIM_INFINITY || new_mem_lim < rl.rlim_max){
+                rl.rlim_cur = new_mem_lim;
+                if (setrlimit(RLIMIT_AS, &rl) == -1)
+                    printf("c WARNING! Could not set resource limit: Virtual memory.\n");
+            } }
+        
+        if (argc == 1)
+            printf("c Reading from standard input... Use '--help' for help.\n");
+        
+        gzFile in = (argc == 1) ? gzdopen(0, "rb") : gzopen(argv[1], "rb");
+        if (in == NULL)
+            printf("c ERROR! Could not open file: %s\n", argc == 1 ? "<stdin>" : argv[1]), exit(1);
+        
+        if (S.verbosity > 0){
+            printf("c ============================[ Problem Statistics ]=============================\n");
+            printf("c |                                                                             |\n"); }
+        
+        parse_DIMACS(in, S);
+        gzclose(in);
+        FILE* res = (argc >= 3) ? fopen(argv[2], "wb") : NULL;
+        
+        if (S.verbosity > 0){
+            printf("c |  Number of variables:  %12d                                         |\n", S.nVars());
+            printf("c |  Number of clauses:    %12d                                         |\n", S.nClauses()); }
+        
+        double parsed_time = cpuTime();
+        if (S.verbosity > 0){
+            printf("c |  Parse time:           %12.2f s                                       |\n", parsed_time - initial_time);
+            printf("c |                                                                             |\n"); }
+
+        // Change to signal-handlers that will only notify the solver and allow it to terminate
+        // voluntarily:
+        signal(SIGINT, SIGINT_interrupt);
+        signal(SIGXCPU,SIGINT_interrupt);
+
+        if (!S.simplify()){
+            if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res);
+            if (S.verbosity > 0){
+                printf("c ===============================================================================\n");
+                printf("c Solved by unit propagation\n");
+                printStats(S);
+                printf("\n"); }
+            printf("s UNSATISFIABLE\n");
+            exit(20);
+        }
+        
+        vec<Lit> dummy;
+        lbool ret = S.solveLimited(dummy);
+        if (S.verbosity > 0){
+            printStats(S);
+            if (ret == l_True) {
+                in = (argc == 1) ? gzdopen(0, "rb") : gzopen(argv[1], "rb");
+                check_solution_DIMACS(in, S);
+                gzclose(in);
+            }
+            printf("\n"); }
+        printf(ret == l_True ? "s SATISFIABLE\n" : ret == l_False ? "s UNSATISFIABLE\n" : "s UNKNOWN\n");
+        if (ret == l_True){
+            printf("v ");
+            for (int i = 0; i < S.nVars(); i++)
+                if (S.model[i] != l_Undef)
+                    printf("%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1);
+            printf(" 0\n");
+        }
+
+
+        if (res != NULL){
+            if (ret == l_True){
+                fprintf(res, "SAT\n");
+                for (int i = 0; i < S.nVars(); i++)
+                    if (S.model[i] != l_Undef)
+                        fprintf(res, "%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1);
+                fprintf(res, " 0\n");
+            }else if (ret == l_False)
+                fprintf(res, "UNSAT\n");
+            else
+                fprintf(res, "INDET\n");
+            fclose(res);
+        }
+        
+#ifdef NDEBUG
+        exit(ret == l_True ? 10 : ret == l_False ? 20 : 0);     // (faster than "return", which will invoke the destructor for 'Solver')
+#else
+        return (ret == l_True ? 10 : ret == l_False ? 20 : 0);
+#endif
+    } catch (OutOfMemoryException&){
+        printf("c ===============================================================================\n");
+        printf("s UNKNOWN\n");
+        exit(0);
+    }
+}

+ 5 - 0
sources/core/Makefile

@@ -0,0 +1,5 @@
+EXEC      = ReasonLS
+DEPDIR    = mtl utils
+MROOT     = ..
+
+include $(MROOT)/mtl/template.mk

+ 2611 - 0
sources/core/Solver.cc

@@ -0,0 +1,2611 @@
+/***************************************************************************************[Solver.cc]
+MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+           Copyright (c) 2007-2010, Niklas Sorensson
+ 
+Chanseok Oh's MiniSat Patch Series -- Copyright (c) 2015, Chanseok Oh
+ 
+Maple_LCM, Based on MapleCOMSPS_DRUP -- Copyright (c) 2017, Mao Luo, Chu-Min LI, Fan Xiao: implementing a learnt clause minimisation approach
+Reference: M. Luo, C.-M. Li, F. Xiao, F. Manya, and Z. L. , “An effective learnt clause minimization approach for cdcl sat solvers,” in IJCAI-2017, 2017, pp. to–appear.
+
+Maple_LCM_Dist, Based on Maple_LCM -- Copyright (c) 2017, Fan Xiao, Chu-Min LI, Mao Luo: using a new branching heuristic called Distance at the beginning of search
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#include <math.h>
+#include <signal.h>
+#include <unistd.h>
+
+#include "mtl/Sort.h"
+#include "core/Solver.h"
+
+using namespace Minisat;
+
+#ifdef BIN_DRUP
+int Solver::buf_len = 0;
+unsigned char Solver::drup_buf[2 * 1024 * 1024];
+unsigned char* Solver::buf_ptr = drup_buf;
+#endif
+
+//=================================================================================================
+// Options:
+
+
+static const char* _cat = "CORE";
+
+static DoubleOption  opt_step_size         (_cat, "step-size",   "Initial step size",                             0.40,     DoubleRange(0, false, 1, false));
+static DoubleOption  opt_step_size_dec     (_cat, "step-size-dec","Step size decrement",                          0.000001, DoubleRange(0, false, 1, false));
+static DoubleOption  opt_min_step_size     (_cat, "min-step-size","Minimal step size",                            0.06,     DoubleRange(0, false, 1, false));
+static DoubleOption  opt_var_decay         (_cat, "var-decay",   "The variable activity decay factor",            0.80,     DoubleRange(0, false, 1, false));
+static DoubleOption  opt_clause_decay      (_cat, "cla-decay",   "The clause activity decay factor",              0.999,    DoubleRange(0, false, 1, false));
+static DoubleOption  opt_random_var_freq   (_cat, "rnd-freq",    "The frequency with which the decision heuristic tries to choose a random variable", 0, DoubleRange(0, true, 1, true));
+static DoubleOption  opt_random_seed       (_cat, "rnd-seed",    "Used by the random variable selection",         91648253, DoubleRange(0, false, HUGE_VAL, false));
+static IntOption     opt_ccmin_mode        (_cat, "ccmin-mode",  "Controls conflict clause minimization (0=none, 1=basic, 2=deep)", 2, IntRange(0, 2));
+static IntOption     opt_phase_saving      (_cat, "phase-saving", "Controls the level of phase saving (0=none, 1=limited, 2=full)", 2, IntRange(0, 2));
+static BoolOption    opt_rnd_init_act      (_cat, "rnd-init",    "Randomize the initial activity", false);
+static IntOption     opt_restart_first     (_cat, "rfirst",      "The base restart interval", 100, IntRange(1, INT32_MAX));
+static DoubleOption  opt_restart_inc       (_cat, "rinc",        "Restart interval increase factor", 2, DoubleRange(1, false, HUGE_VAL, false));
+static DoubleOption  opt_garbage_frac      (_cat, "gc-frac",     "The fraction of wasted memory allowed before a garbage collection is triggered",  0.20, DoubleRange(0, false, HUGE_VAL, false));
+
+
+//------------
+static DoubleOption  opt_conflRatio  (_cat, "conflRatio","True assgins above this,construct a model",  0.9, DoubleRange(0, true, 1, true));
+static DoubleOption  opt_areaRatio   (_cat, "areaRatio","Make sure two false model not too nearly in search space",  1.01, DoubleRange(1, true, 3, true));
+static DoubleOption  opt_maxflipRatio(_cat,"maxFlipRatio","max steps for cnnr",  600, DoubleRange(1, true, 50000, true));
+static DoubleOption  opt_lastflipRatio(_cat,"initFlipRatio","initial & now steps",  100, DoubleRange(1, true, 50000, true));
+static DoubleOption  opt_timeRatio    (_cat,"timeRatio","cnnrTime / totalTime",  0.35, DoubleRange(0, true, 1.5, true));
+static DoubleOption  opt_raiseFlipRatio(_cat,"raiseFlipRatio","lastflipRatio*=raiseFlipRatio every time call cnnr",  1.02, DoubleRange(1, true, 5, true));
+static DoubleOption  opt_switchMode(_cat,"switchMode","time to switch to VSIDS",  2500, DoubleRange(0, true, 6000, true));
+
+//==============
+
+
+
+//=================================================================================================
+// Constructor/Destructor:
+
+
+Solver::Solver() :
+
+    // Parameters (user settable):
+    //
+    drup_file        (NULL)
+  , verbosity        (0)
+  , step_size        (opt_step_size)
+  , step_size_dec    (opt_step_size_dec)
+  , min_step_size    (opt_min_step_size)
+  , timer            (5000)
+  , var_decay        (opt_var_decay)
+  , clause_decay     (opt_clause_decay)
+  , random_var_freq  (opt_random_var_freq)
+  , random_seed      (opt_random_seed)
+  , VSIDS            (false)
+  , ccmin_mode       (opt_ccmin_mode)
+  , phase_saving     (opt_phase_saving)
+  , rnd_pol          (false)
+  , rnd_init_act     (opt_rnd_init_act)
+  , garbage_frac     (opt_garbage_frac)
+  , restart_first    (opt_restart_first)
+  , restart_inc      (opt_restart_inc)
+
+  // Parameters (the rest):
+  //
+  , learntsize_factor((double)1/(double)3), learntsize_inc(1.1)
+
+  // Parameters (experimental):
+  //
+  , learntsize_adjust_start_confl (100)
+  , learntsize_adjust_inc         (1.5)
+
+  // Statistics: (formerly in 'SolverStats')
+  //
+  , solves(0), starts(0), decisions(0), rnd_decisions(0), propagations(0), conflicts(0), conflicts_VSIDS(0)
+  , dec_vars(0), clauses_literals(0), learnts_literals(0), max_literals(0), tot_literals(0)
+
+  , ok                 (true)
+  , cla_inc            (1)
+  , var_inc            (1)
+  , watches_bin        (WatcherDeleted(ca))
+  , watches            (WatcherDeleted(ca))
+  , qhead              (0)
+  , simpDB_assigns     (-1)
+  , simpDB_props       (0)
+  , order_heap_CHB     (VarOrderLt(activity_CHB))
+  , order_heap_VSIDS   (VarOrderLt(activity_VSIDS))
+  , progress_estimate  (0)
+  , remove_satisfied   (true)
+
+  , core_lbd_cut       (3)
+  , global_lbd_sum     (0)
+  , lbd_queue          (50)
+  , next_T2_reduce     (10000)
+  , next_L_reduce      (15000)
+  
+  , counter            (0)
+
+  // Resource constraints:
+  //
+  , conflict_budget    (-1)
+  , propagation_budget (-1)
+  , asynch_interrupt   (false)
+
+  // simplfiy
+  , nbSimplifyAll(0)
+  , s_propagations(0)
+
+  // simplifyAll adjust occasion
+  , curSimplify(1)
+  , nbconfbeforesimplify(1000)
+  , incSimplify(1000)
+
+  , my_var_decay       (0.6)
+  , DISTANCE           (true)
+  , var_iLevel_inc     (1)
+  , order_heap_distance(VarOrderLt(activity_distance))
+//------------------------------
+  , areaRatio           (opt_areaRatio)
+  , conflRatio          (opt_conflRatio)
+  , maxflipRatio        (opt_maxflipRatio)
+  , lastflipRatio       (opt_lastflipRatio)
+  , raiseFlipRatio      (opt_raiseFlipRatio)
+  , timeRatio           (opt_timeRatio)
+  , maxstep             (20000000)
+  , UnComTime           (0.0)
+  , callNum             (0)
+  , solvedByUncom       (false)
+  , forceRestart        (false)
+  , lastLearntNum       (0)
+//=============================
+{
+    //--------------------------------
+    //adjust
+    //ifstream fin("para");
+    //fin>>conflRatio>>areaRatio>>maxstep>>maxflipRatio>>lastflipRatio>>raiseFlipRatio>>timeLimit>>timeRatio;
+
+    //printf("%f %f %ld %f %f %f\n",conflRatio,areaRatio,maxstep,maxflipRatio,lastflipRatio,raiseFlipRatio);
+    //fin.close();
+    //===============================
+
+
+}
+
+
+Solver::~Solver()
+{
+}
+
+
+// simplify All
+//
+CRef Solver::simplePropagate()
+{
+    CRef    confl = CRef_Undef;
+    int     num_props = 0;
+    watches.cleanAll();
+    watches_bin.cleanAll();
+    while (qhead < trail.size())
+    {
+        Lit            p = trail[qhead++];     // 'p' is enqueued fact to propagate.
+        vec<Watcher>&  ws = watches[p];
+        Watcher        *i, *j, *end;
+        num_props++;
+
+
+        // First, Propagate binary clauses
+        vec<Watcher>&  wbin = watches_bin[p];
+
+        for (int k = 0; k<wbin.size(); k++)
+        {
+
+            Lit imp = wbin[k].blocker;
+
+            if (value(imp) == l_False)
+            {
+                return wbin[k].cref;
+            }
+
+            if (value(imp) == l_Undef)
+            {
+                simpleUncheckEnqueue(imp, wbin[k].cref);
+            }
+        }
+        for (i = j = (Watcher*)ws, end = i + ws.size(); i != end;)
+        {
+            // Try to avoid inspecting the clause:
+            Lit blocker = i->blocker;
+            if (value(blocker) == l_True)
+            {
+                *j++ = *i++; continue;
+            }
+
+            // Make sure the false literal is data[1]:
+            CRef     cr = i->cref;
+            Clause&  c = ca[cr];
+            Lit      false_lit = ~p;
+            if (c[0] == false_lit)
+                c[0] = c[1], c[1] = false_lit;
+            assert(c[1] == false_lit);
+            //  i++;
+
+            // If 0th watch is true, then clause is already satisfied.
+            // However, 0th watch is not the blocker, make it blocker using a new watcher w
+            // why not simply do i->blocker=first in this case?
+            Lit     first = c[0];
+            //  Watcher w     = Watcher(cr, first);
+            if (first != blocker && value(first) == l_True)
+            {
+                i->blocker = first;
+                *j++ = *i++; continue;
+            }
+
+            // Look for new watch:
+            //if (incremental)
+            //{ // ----------------- INCREMENTAL MODE
+            //	int choosenPos = -1;
+            //	for (int k = 2; k < c.size(); k++)
+            //	{
+            //		if (value(c[k]) != l_False)
+            //		{
+            //			if (decisionLevel()>assumptions.size())
+            //			{
+            //				choosenPos = k;
+            //				break;
+            //			}
+            //			else
+            //			{
+            //				choosenPos = k;
+
+            //				if (value(c[k]) == l_True || !isSelector(var(c[k]))) {
+            //					break;
+            //				}
+            //			}
+
+            //		}
+            //	}
+            //	if (choosenPos != -1)
+            //	{
+            //		// watcher i is abandonned using i++, because cr watches now ~c[k] instead of p
+            //		// the blocker is first in the watcher. However,
+            //		// the blocker in the corresponding watcher in ~first is not c[1]
+            //		Watcher w = Watcher(cr, first); i++;
+            //		c[1] = c[choosenPos]; c[choosenPos] = false_lit;
+            //		watches[~c[1]].push(w);
+            //		goto NextClause;
+            //	}
+            //}
+            else
+            {  // ----------------- DEFAULT  MODE (NOT INCREMENTAL)
+                for (int k = 2; k < c.size(); k++)
+                {
+
+                    if (value(c[k]) != l_False)
+                    {
+                        // watcher i is abandonned using i++, because cr watches now ~c[k] instead of p
+                        // the blocker is first in the watcher. However,
+                        // the blocker in the corresponding watcher in ~first is not c[1]
+                        Watcher w = Watcher(cr, first); i++;
+                        c[1] = c[k]; c[k] = false_lit;
+                        watches[~c[1]].push(w);
+                        goto NextClause;
+                    }
+                }
+            }
+
+            // Did not find watch -- clause is unit under assignment:
+            i->blocker = first;
+            *j++ = *i++;
+            if (value(first) == l_False)
+            {
+                confl = cr;
+                qhead = trail.size();
+                // Copy the remaining watches:
+                while (i < end)
+                    *j++ = *i++;
+            }
+            else
+            {
+                simpleUncheckEnqueue(first, cr);
+            }
+NextClause:;
+        }
+        ws.shrink(i - j);
+    }
+
+    s_propagations += num_props;
+
+    return confl;
+}
+
+void Solver::simpleUncheckEnqueue(Lit p, CRef from){
+    assert(value(p) == l_Undef);
+    assigns[var(p)] = lbool(!sign(p)); // this makes a lbool object whose value is sign(p)
+    vardata[var(p)].reason = from;
+    trail.push_(p);
+}
+
+void Solver::cancelUntilTrailRecord()
+{
+    for (int c = trail.size() - 1; c >= trailRecord; c--)
+    {
+        Var x = var(trail[c]);
+        assigns[x] = l_Undef;
+
+    }
+    qhead = trailRecord;
+    trail.shrink(trail.size() - trailRecord);
+
+}
+
+void Solver::litsEnqueue(int cutP, Clause& c)
+{
+    for (int i = cutP; i < c.size(); i++)
+    {
+        simpleUncheckEnqueue(~c[i]);
+    }
+}
+
+bool Solver::removed(CRef cr) {
+    return ca[cr].mark() == 1;
+}
+
+void Solver::simpleAnalyze(CRef confl, vec<Lit>& out_learnt, vec<CRef>& reason_clause, bool True_confl)
+{
+    int pathC = 0;
+    Lit p = lit_Undef;
+    int index = trail.size() - 1;
+
+    do{
+        if (confl != CRef_Undef){
+            reason_clause.push(confl);
+            Clause& c = ca[confl];
+            // Special case for binary clauses
+            // The first one has to be SAT
+            if (p != lit_Undef && c.size() == 2 && value(c[0]) == l_False) {
+
+                assert(value(c[1]) == l_True);
+                Lit tmp = c[0];
+                c[0] = c[1], c[1] = tmp;
+            }
+            // if True_confl==true, then choose p begin with the 1th index of c;
+            for (int j = (p == lit_Undef && True_confl == false) ? 0 : 1; j < c.size(); j++){
+                Lit q = c[j];
+                if (!seen[var(q)]){
+                    seen[var(q)] = 1;
+                    pathC++;
+                }
+            }
+        }
+        else if (confl == CRef_Undef){
+            out_learnt.push(~p);
+        }
+        // if not break, while() will come to the index of trail blow 0, and fatal error occur;
+        if (pathC == 0) break;
+        // Select next clause to look at:
+        while (!seen[var(trail[index--])]);
+        // if the reason cr from the 0-level assigned var, we must break avoid move forth further;
+        // but attention that maybe seen[x]=1 and never be clear. However makes no matter;
+        if (trailRecord > index + 1) break;
+        p = trail[index + 1];
+        confl = reason(var(p));
+        seen[var(p)] = 0;
+        pathC--;
+
+    } while (pathC >= 0);
+}
+
+void Solver::simplifyLearnt(Clause& c)
+{
+    ////
+    original_length_record += c.size();
+
+    trailRecord = trail.size();// record the start pointer
+
+    vec<Lit> falseLit;
+    falseLit.clear();
+
+    //sort(&c[0], c.size(), VarOrderLevelLt(vardata));
+
+    bool True_confl = false;
+    int beforeSize, afterSize;
+    beforeSize = c.size();
+    int i, j;
+    CRef confl;
+
+    for (i = 0, j = 0; i < c.size(); i++){
+        if (value(c[i]) == l_Undef){
+            //printf("///@@@ uncheckedEnqueue:index = %d. l_Undef\n", i);
+            simpleUncheckEnqueue(~c[i]);
+            c[j++] = c[i];
+            confl = simplePropagate();
+            if (confl != CRef_Undef){
+                break;
+            }
+        }
+        else{
+            if (value(c[i]) == l_True){
+                //printf("///@@@ uncheckedEnqueue:index = %d. l_True\n", i);
+                c[j++] = c[i];
+                True_confl = true;
+                confl = reason(var(c[i]));
+                break;
+            }
+            else{
+                //printf("///@@@ uncheckedEnqueue:index = %d. l_False\n", i);
+                falseLit.push(c[i]);
+            }
+        }
+    }
+    c.shrink(c.size() - j);
+    afterSize = c.size();
+    //printf("\nbefore : %d, after : %d ", beforeSize, afterSize);
+
+
+    if (confl != CRef_Undef || True_confl == true){
+        simp_learnt_clause.clear();
+        simp_reason_clause.clear();
+        if (True_confl == true){
+            simp_learnt_clause.push(c.last());
+        }
+        simpleAnalyze(confl, simp_learnt_clause, simp_reason_clause, True_confl);
+
+        if (simp_learnt_clause.size() < c.size()){
+            for (i = 0; i < simp_learnt_clause.size(); i++){
+                c[i] = simp_learnt_clause[i];
+            }
+            c.shrink(c.size() - i);
+        }
+    }
+
+    cancelUntilTrailRecord();
+
+    ////
+    simplified_length_record += c.size();
+
+}
+
+bool Solver::simplifyLearnt_x(vec<CRef>& learnts_x)
+{
+    int beforeSize, afterSize;
+    int learnts_x_size_before = learnts_x.size();
+
+    int ci, cj, li, lj;
+    bool sat, false_lit;
+    unsigned int nblevels;
+    ////
+    //printf("learnts_x size : %d\n", learnts_x.size());
+
+    ////
+    int nbSimplified = 0;
+    int nbSimplifing = 0;
+
+    for (ci = 0, cj = 0; ci < learnts_x.size(); ci++){
+        CRef cr = learnts_x[ci];
+        Clause& c = ca[cr];
+
+        if (removed(cr)) continue;
+        else if (c.simplified()){
+            learnts_x[cj++] = learnts_x[ci];
+            ////
+            nbSimplified++;
+        }
+        else{
+            ////
+            nbSimplifing++;
+            sat = false_lit = false;
+            for (int i = 0; i < c.size(); i++){
+                if (value(c[i]) == l_True){
+                    sat = true;
+                    break;
+                }
+                else if (value(c[i]) == l_False){
+                    false_lit = true;
+                }
+            }
+            if (sat){
+                removeClause(cr);
+            }
+            else{
+                detachClause(cr, true);
+
+                if (false_lit){
+                    for (li = lj = 0; li < c.size(); li++){
+                        if (value(c[li]) != l_False){
+                            c[lj++] = c[li];
+                        }
+                    }
+                    c.shrink(li - lj);
+                }
+
+                beforeSize = c.size();
+                assert(c.size() > 1);
+                // simplify a learnt clause c
+                simplifyLearnt(c);
+                assert(c.size() > 0);
+                afterSize = c.size();
+
+                //printf("beforeSize: %2d, afterSize: %2d\n", beforeSize, afterSize);
+
+                if (c.size() == 1){
+                    // when unit clause occur, enqueue and propagate
+                    uncheckedEnqueue(c[0]);
+                    if (propagate() != CRef_Undef){
+                        ok = false;
+                        return false;
+                    }
+                    // delete the clause memory in logic
+                    c.mark(1);
+                    ca.free(cr);
+                }
+                else{
+                    attachClause(cr);
+                    learnts_x[cj++] = learnts_x[ci];
+
+                    nblevels = computeLBD(c);
+                    if (nblevels < c.lbd()){
+                        //printf("lbd-before: %d, lbd-after: %d\n", c.lbd(), nblevels);
+                        c.set_lbd(nblevels);
+                    }
+                    if (c.mark() != CORE){
+                        if (c.lbd() <= core_lbd_cut){
+                            //if (c.mark() == LOCAL) local_learnts_dirty = true;
+                            //else tier2_learnts_dirty = true;
+                            cj--;
+                            learnts_core.push(cr);
+                            c.mark(CORE);
+                        }
+                        else if (c.mark() == LOCAL && c.lbd() <= 6){
+                            //local_learnts_dirty = true;
+                            cj--;
+                            learnts_tier2.push(cr);
+                            c.mark(TIER2);
+                        }
+                    }
+
+                    c.setSimplified(true);
+                }
+            }
+        }
+    }
+    learnts_x.shrink(ci - cj);
+
+    //   printf("c nbLearnts_x %d / %d, nbSimplified: %d, nbSimplifing: %d\n",
+    //          learnts_x_size_before, learnts_x.size(), nbSimplified, nbSimplifing);
+
+    return true;
+}
+
+bool Solver::simplifyLearnt_core()
+{
+    int beforeSize, afterSize;
+    int learnts_core_size_before = learnts_core.size();
+
+    int ci, cj, li, lj;
+    bool sat, false_lit;
+    unsigned int nblevels;
+    ////
+    //printf("learnts_x size : %d\n", learnts_x.size());
+
+    ////
+    int nbSimplified = 0;
+    int nbSimplifing = 0;
+
+    for (ci = 0, cj = 0; ci < learnts_core.size(); ci++){
+        CRef cr = learnts_core[ci];
+        Clause& c = ca[cr];
+
+        if (removed(cr)) continue;
+        else if (c.simplified()){
+            learnts_core[cj++] = learnts_core[ci];
+            ////
+            nbSimplified++;
+        }
+        else{
+            int saved_size=c.size();
+            //         if (drup_file){
+            //                 add_oc.clear();
+            //                 for (int i = 0; i < c.size(); i++) add_oc.push(c[i]); }
+            ////
+            nbSimplifing++;
+            sat = false_lit = false;
+            for (int i = 0; i < c.size(); i++){
+                if (value(c[i]) == l_True){
+                    sat = true;
+                    break;
+                }
+                else if (value(c[i]) == l_False){
+                    false_lit = true;
+                }
+            }
+            if (sat){
+                removeClause(cr);
+            }
+            else{
+                detachClause(cr, true);
+
+                if (false_lit){
+                    for (li = lj = 0; li < c.size(); li++){
+                        if (value(c[li]) != l_False){
+                            c[lj++] = c[li];
+                        }
+                    }
+                    c.shrink(li - lj);
+                }
+
+                beforeSize = c.size();
+                assert(c.size() > 1);
+                // simplify a learnt clause c
+                simplifyLearnt(c);
+                assert(c.size() > 0);
+                afterSize = c.size();
+                
+                if(saved_size !=c.size()){
+
+#ifdef BIN_DRUP
+                    binDRUP('a', c , drup_file);
+                    //                    binDRUP('d', add_oc, drup_file);
+#else
+                    for (int i = 0; i < c.size(); i++)
+                        fprintf(drup_file, "%i ", (var(c[i]) + 1) * (-2 * sign(c[i]) + 1));
+                    fprintf(drup_file, "0\n");
+
+                    //                    fprintf(drup_file, "d ");
+                    //                    for (int i = 0; i < add_oc.size(); i++)
+                    //                        fprintf(drup_file, "%i ", (var(add_oc[i]) + 1) * (-2 * sign(add_oc[i]) + 1));
+                    //                    fprintf(drup_file, "0\n");
+#endif
+                }
+
+                //printf("beforeSize: %2d, afterSize: %2d\n", beforeSize, afterSize);
+
+                if (c.size() == 1){
+                    // when unit clause occur, enqueue and propagate
+                    uncheckedEnqueue(c[0]);
+                    if (propagate() != CRef_Undef){
+                        ok = false;
+                        return false;
+                    }
+                    // delete the clause memory in logic
+                    c.mark(1);
+                    ca.free(cr);
+//#ifdef BIN_DRUP
+//                    binDRUP('d', c, drup_file);
+//#else
+//                    fprintf(drup_file, "d ");
+//                    for (int i = 0; i < c.size(); i++)
+//                        fprintf(drup_file, "%i ", (var(c[i]) + 1) * (-2 * sign(c[i]) + 1));
+//                    fprintf(drup_file, "0\n");
+//#endif
+                }
+                else{
+                    attachClause(cr);
+                    learnts_core[cj++] = learnts_core[ci];
+
+                    nblevels = computeLBD(c);
+                    if (nblevels < c.lbd()){
+                        //printf("lbd-before: %d, lbd-after: %d\n", c.lbd(), nblevels);
+                        c.set_lbd(nblevels);
+                    }
+
+                    c.setSimplified(true);
+                }
+            }
+        }
+    }
+    learnts_core.shrink(ci - cj);
+
+    //    printf("c nbLearnts_core %d / %d, nbSimplified: %d, nbSimplifing: %d\n",
+    //           learnts_core_size_before, learnts_core.size(), nbSimplified, nbSimplifing);
+
+    return true;
+
+}
+
+bool Solver::simplifyLearnt_tier2()
+{
+    int beforeSize, afterSize;
+    int learnts_tier2_size_before = learnts_tier2.size();
+
+    int ci, cj, li, lj;
+    bool sat, false_lit;
+    unsigned int nblevels;
+    ////
+    //printf("learnts_x size : %d\n", learnts_x.size());
+
+    ////
+    int nbSimplified = 0;
+    int nbSimplifing = 0;
+
+    for (ci = 0, cj = 0; ci < learnts_tier2.size(); ci++){
+        CRef cr = learnts_tier2[ci];
+        Clause& c = ca[cr];
+
+        if (removed(cr)) continue;
+        else if (c.simplified()){
+            learnts_tier2[cj++] = learnts_tier2[ci];
+            ////
+            nbSimplified++;
+        }
+        else{
+            int saved_size=c.size();
+            //            if (drup_file){
+            //                    add_oc.clear();
+            //                    for (int i = 0; i < c.size(); i++) add_oc.push(c[i]); }
+            ////
+            nbSimplifing++;
+            sat = false_lit = false;
+            for (int i = 0; i < c.size(); i++){
+                if (value(c[i]) == l_True){
+                    sat = true;
+                    break;
+                }
+                else if (value(c[i]) == l_False){
+                    false_lit = true;
+                }
+            }
+            if (sat){
+                removeClause(cr);
+            }
+            else{
+                detachClause(cr, true);
+
+                if (false_lit){
+                    for (li = lj = 0; li < c.size(); li++){
+                        if (value(c[li]) != l_False){
+                            c[lj++] = c[li];
+                        }
+                    }
+                    c.shrink(li - lj);
+                }
+
+                beforeSize = c.size();
+                assert(c.size() > 1);
+                // simplify a learnt clause c
+                simplifyLearnt(c);
+                assert(c.size() > 0);
+                afterSize = c.size();
+                
+                if(saved_size!=c.size()){
+
+#ifdef BIN_DRUP
+                    binDRUP('a', c , drup_file);
+                    //                    binDRUP('d', add_oc, drup_file);
+#else
+                    for (int i = 0; i < c.size(); i++)
+                        fprintf(drup_file, "%i ", (var(c[i]) + 1) * (-2 * sign(c[i]) + 1));
+                    fprintf(drup_file, "0\n");
+
+                    //                    fprintf(drup_file, "d ");
+                    //                    for (int i = 0; i < add_oc.size(); i++)
+                    //                        fprintf(drup_file, "%i ", (var(add_oc[i]) + 1) * (-2 * sign(add_oc[i]) + 1));
+                    //                    fprintf(drup_file, "0\n");
+#endif
+                }
+
+                //printf("beforeSize: %2d, afterSize: %2d\n", beforeSize, afterSize);
+
+                if (c.size() == 1){
+                    // when unit clause occur, enqueue and propagate
+                    uncheckedEnqueue(c[0]);
+                    if (propagate() != CRef_Undef){
+                        ok = false;
+                        return false;
+                    }
+                    // delete the clause memory in logic
+                    c.mark(1);
+                    ca.free(cr);
+//#ifdef BIN_DRUP
+//                    binDRUP('d', c, drup_file);
+//#else
+//                    fprintf(drup_file, "d ");
+//                    for (int i = 0; i < c.size(); i++)
+//                        fprintf(drup_file, "%i ", (var(c[i]) + 1) * (-2 * sign(c[i]) + 1));
+//                    fprintf(drup_file, "0\n");
+//#endif
+                }
+                else{
+                    attachClause(cr);
+                    learnts_tier2[cj++] = learnts_tier2[ci];
+
+                    nblevels = computeLBD(c);
+                    if (nblevels < c.lbd()){
+                        //printf("lbd-before: %d, lbd-after: %d\n", c.lbd(), nblevels);
+                        c.set_lbd(nblevels);
+                    }
+
+                    if (c.lbd() <= core_lbd_cut){
+                        cj--;
+                        learnts_core.push(cr);
+                        c.mark(CORE);
+                    }
+
+                    c.setSimplified(true);
+                }
+            }
+        }
+    }
+    learnts_tier2.shrink(ci - cj);
+
+    //    printf("c nbLearnts_tier2 %d / %d, nbSimplified: %d, nbSimplifing: %d\n",
+    //           learnts_tier2_size_before, learnts_tier2.size(), nbSimplified, nbSimplifing);
+
+    return true;
+
+}
+
+bool Solver::simplifyAll()
+{
+    ////
+    simplified_length_record = original_length_record = 0;
+
+    if (!ok || propagate() != CRef_Undef)
+        return ok = false;
+
+    //// cleanLearnts(also can delete these code), here just for analyzing
+    //if (local_learnts_dirty) cleanLearnts(learnts_local, LOCAL);
+    //if (tier2_learnts_dirty) cleanLearnts(learnts_tier2, TIER2);
+    //local_learnts_dirty = tier2_learnts_dirty = false;
+
+    if (!simplifyLearnt_core()) return ok = false;
+    if (!simplifyLearnt_tier2()) return ok = false;
+    //if (!simplifyLearnt_x(learnts_local)) return ok = false;
+
+    checkGarbage();
+
+    ////
+    //  printf("c size_reduce_ratio     : %4.2f%%\n",
+    //         original_length_record == 0 ? 0 : (original_length_record - simplified_length_record) * 100 / (double)original_length_record);
+
+
+    //-----------------------------
+    if(lastLearntNum > nLearnts()){
+        lastLearntNum = nLearnts();
+    }
+    //=============================
+
+
+    return true;
+}
+//=================================================================================================
+// Minor methods:
+
+
+// Creates a new SAT variable in the solver. If 'decision' is cleared, variable will not be
+// used as a decision variable (NOTE! This has effects on the meaning of a SATISFIABLE result).
+//
+Var Solver::newVar(bool sign, bool dvar)
+{
+    int v = nVars();
+    watches_bin.init(mkLit(v, false));
+    watches_bin.init(mkLit(v, true ));
+    watches  .init(mkLit(v, false));
+    watches  .init(mkLit(v, true ));
+    assigns  .push(l_Undef);
+    vardata  .push(mkVarData(CRef_Undef, 0));
+    activity_CHB  .push(0);
+    activity_VSIDS.push(rnd_init_act ? drand(random_seed) * 0.00001 : 0);
+
+    picked.push(0);
+    conflicted.push(0);
+    almost_conflicted.push(0);
+#ifdef ANTI_EXPLORATION
+    canceled.push(0);
+#endif
+
+    seen     .push(0);
+    seen2    .push(0);
+    polarity .push(sign);
+    decision .push();
+    trail    .capacity(v+1);
+    setDecisionVar(v, dvar);
+
+    activity_distance.push(0);
+    var_iLevel.push(0);
+    var_iLevel_tmp.push(0);
+    pathCs.push(0);
+    return v;
+}
+
+
+bool Solver::addClause_(vec<Lit>& ps)
+{
+    assert(decisionLevel() == 0);
+    if (!ok) return false;
+
+    // Check if clause is satisfied and remove false/duplicate literals:
+    sort(ps);
+    Lit p; int i, j;
+
+    if (drup_file){
+        add_oc.clear();
+        for (int i = 0; i < ps.size(); i++) add_oc.push(ps[i]); }
+
+    for (i = j = 0, p = lit_Undef; i < ps.size(); i++)
+        if (value(ps[i]) == l_True || ps[i] == ~p)
+            return true;
+        else if (value(ps[i]) != l_False && ps[i] != p)
+            ps[j++] = p = ps[i];
+    ps.shrink(i - j);
+
+    if (drup_file && i != j){
+#ifdef BIN_DRUP
+        binDRUP('a', ps, drup_file);
+        binDRUP('d', add_oc, drup_file);
+#else
+        for (int i = 0; i < ps.size(); i++)
+            fprintf(drup_file, "%i ", (var(ps[i]) + 1) * (-2 * sign(ps[i]) + 1));
+        fprintf(drup_file, "0\n");
+
+        fprintf(drup_file, "d ");
+        for (int i = 0; i < add_oc.size(); i++)
+            fprintf(drup_file, "%i ", (var(add_oc[i]) + 1) * (-2 * sign(add_oc[i]) + 1));
+        fprintf(drup_file, "0\n");
+#endif
+    }
+
+    if (ps.size() == 0)
+        return ok = false;
+    else if (ps.size() == 1){
+        uncheckedEnqueue(ps[0]);
+        return ok = (propagate() == CRef_Undef);
+    }else{
+        CRef cr = ca.alloc(ps, false);
+        clauses.push(cr);
+        attachClause(cr);
+    }
+
+    return true;
+}
+
+
+void Solver::attachClause(CRef cr) {
+    const Clause& c = ca[cr];
+    assert(c.size() > 1);
+    OccLists<Lit, vec<Watcher>, WatcherDeleted>& ws = c.size() == 2 ? watches_bin : watches;
+    ws[~c[0]].push(Watcher(cr, c[1]));
+    ws[~c[1]].push(Watcher(cr, c[0]));
+    if (c.learnt()) learnts_literals += c.size();
+    else            clauses_literals += c.size(); }
+
+
+void Solver::detachClause(CRef cr, bool strict) {
+    const Clause& c = ca[cr];
+    assert(c.size() > 1);
+    OccLists<Lit, vec<Watcher>, WatcherDeleted>& ws = c.size() == 2 ? watches_bin : watches;
+    
+    if (strict){
+        remove(ws[~c[0]], Watcher(cr, c[1]));
+        remove(ws[~c[1]], Watcher(cr, c[0]));
+    }else{
+        // Lazy detaching: (NOTE! Must clean all watcher lists before garbage collecting this clause)
+        ws.smudge(~c[0]);
+        ws.smudge(~c[1]);
+    }
+
+    if (c.learnt()) learnts_literals -= c.size();
+    else            clauses_literals -= c.size(); }
+
+
+void Solver::removeClause(CRef cr) {
+    Clause& c = ca[cr];
+
+    if (drup_file){
+        if (c.mark() != 1){
+#ifdef BIN_DRUP
+            binDRUP('d', c, drup_file);
+#else
+            fprintf(drup_file, "d ");
+            for (int i = 0; i < c.size(); i++)
+                fprintf(drup_file, "%i ", (var(c[i]) + 1) * (-2 * sign(c[i]) + 1));
+            fprintf(drup_file, "0\n");
+#endif
+        }else
+            printf("c Bug. I don't expect this to happen.\n");
+    }
+
+    detachClause(cr);
+    // Don't leave pointers to free'd memory!
+    if (locked(c)){
+        Lit implied = c.size() != 2 ? c[0] : (value(c[0]) == l_True ? c[0] : c[1]);
+        vardata[var(implied)].reason = CRef_Undef; }
+    c.mark(1);
+    ca.free(cr);
+}
+
+
+bool Solver::satisfied(const Clause& c) const {
+    for (int i = 0; i < c.size(); i++)
+        if (value(c[i]) == l_True)
+            return true;
+    return false; }
+
+
+// Revert to the state at given level (keeping all assignment at 'level' but not beyond).
+//
+void Solver::cancelUntil(int level) {
+    if (decisionLevel() > level){
+        for (int c = trail.size()-1; c >= trail_lim[level]; c--){
+            Var      x  = var(trail[c]);
+
+            if (!VSIDS){
+                uint32_t age = conflicts - picked[x];
+                if (age > 0){
+                    double adjusted_reward = ((double) (conflicted[x] + almost_conflicted[x])) / ((double) age);
+                    double old_activity = activity_CHB[x];
+                    activity_CHB[x] = step_size * adjusted_reward + ((1 - step_size) * old_activity);
+                    if (order_heap_CHB.inHeap(x)){
+                        if (activity_CHB[x] > old_activity)
+                            order_heap_CHB.decrease(x);
+                        else
+                            order_heap_CHB.increase(x);
+                    }
+                }
+#ifdef ANTI_EXPLORATION
+                canceled[x] = conflicts;
+#endif
+            }
+
+            assigns [x] = l_Undef;
+            if (phase_saving > 1 || (phase_saving == 1) && c > trail_lim.last())
+                polarity[x] = sign(trail[c]);
+            insertVarOrder(x); }
+        qhead = trail_lim[level];
+        trail.shrink(trail.size() - trail_lim[level]);
+        trail_lim.shrink(trail_lim.size() - level);
+    } }
+
+
+//=================================================================================================
+// Major methods:
+
+
+Lit Solver::pickBranchLit()
+{
+    Var next = var_Undef;
+    //    Heap<VarOrderLt>& order_heap = VSIDS ? order_heap_VSIDS : order_heap_CHB;
+    Heap<VarOrderLt>& order_heap = DISTANCE ? order_heap_distance : ((!VSIDS)? order_heap_CHB:order_heap_VSIDS);
+
+    // Random decision:
+    /*if (drand(random_seed) < random_var_freq && !order_heap.empty()){
+        next = order_heap[irand(random_seed,order_heap.size())];
+        if (value(next) == l_Undef && decision[next])
+            rnd_decisions++; }*/
+
+    // Activity based decision:
+    while (next == var_Undef || value(next) != l_Undef || !decision[next])
+        if (order_heap.empty())
+            return lit_Undef;
+        else{
+#ifdef ANTI_EXPLORATION
+            if (!VSIDS){
+                Var v = order_heap_CHB[0];
+                uint32_t age = conflicts - canceled[v];
+                while (age > 0){
+                    double decay = pow(0.95, age);
+                    activity_CHB[v] *= decay;
+                    if (order_heap_CHB.inHeap(v))
+                        order_heap_CHB.increase(v);
+                    canceled[v] = conflicts;
+                    v = order_heap_CHB[0];
+                    age = conflicts - canceled[v];
+                }
+            }
+#endif
+            next = order_heap.removeMin();
+        }
+
+    return mkLit(next, polarity[next]);
+}
+
+
+/*_________________________________________________________________________________________________
+|
+|  analyze : (confl : Clause*) (out_learnt : vec<Lit>&) (out_btlevel : int&)  ->  [void]
+|  
+|  Description:
+|    Analyze conflict and produce a reason clause.
+|  
+|    Pre-conditions:
+|      * 'out_learnt' is assumed to be cleared.
+|      * Current decision level must be greater than root level.
+|  
+|    Post-conditions:
+|      * 'out_learnt[0]' is the asserting literal at level 'out_btlevel'.
+|      * If out_learnt.size() > 1 then 'out_learnt[1]' has the greatest decision level of the 
+|        rest of literals. There may be others from the same level though.
+|  
+|________________________________________________________________________________________________@*/
+void Solver::analyze(CRef confl, vec<Lit>& out_learnt, int& out_btlevel, int& out_lbd)
+{
+    int pathC = 0;
+    Lit p     = lit_Undef;
+
+    // Generate conflict clause:
+    //
+    out_learnt.push();      // (leave room for the asserting literal)
+    int index   = trail.size() - 1;
+
+    do{
+        assert(confl != CRef_Undef); // (otherwise should be UIP)
+        Clause& c = ca[confl];
+
+        // For binary clauses, we don't rearrange literals in propagate(), so check and make sure the first is an implied lit.
+        if (p != lit_Undef && c.size() == 2 && value(c[0]) == l_False){
+            assert(value(c[1]) == l_True);
+            Lit tmp = c[0];
+            c[0] = c[1], c[1] = tmp; }
+
+        // Update LBD if improved.
+        if (c.learnt() && c.mark() != CORE){
+            int lbd = computeLBD(c);
+            if (lbd < c.lbd()){
+                if (c.lbd() <= 30) c.removable(false); // Protect once from reduction.
+                c.set_lbd(lbd);
+                if (lbd <= core_lbd_cut){
+                    learnts_core.push(confl);
+                    c.mark(CORE);
+                }else if (lbd <= 6 && c.mark() == LOCAL){
+                    // Bug: 'cr' may already be in 'learnts_tier2', e.g., if 'cr' was demoted from TIER2
+                    // to LOCAL previously and if that 'cr' is not cleaned from 'learnts_tier2' yet.
+                    learnts_tier2.push(confl);
+                    c.mark(TIER2); }
+            }
+
+            if (c.mark() == TIER2)
+                c.touched() = conflicts;
+            else if (c.mark() == LOCAL)
+                claBumpActivity(c);
+        }
+
+        for (int j = (p == lit_Undef) ? 0 : 1; j < c.size(); j++){
+            Lit q = c[j];
+
+            if (!seen[var(q)] && level(var(q)) > 0){
+                if (VSIDS){
+                    varBumpActivity(var(q), .5);
+                    add_tmp.push(q);
+                }else
+                    conflicted[var(q)]++;
+                seen[var(q)] = 1;
+                if (level(var(q)) >= decisionLevel()){
+                    pathC++;
+                }else
+                    out_learnt.push(q);
+            }
+        }
+        
+        // Select next clause to look at:
+        while (!seen[var(trail[index--])]);
+        p     = trail[index+1];
+        confl = reason(var(p));
+        seen[var(p)] = 0;
+        pathC--;
+
+    }while (pathC > 0);
+    out_learnt[0] = ~p;
+
+    // Simplify conflict clause:
+    //
+    int i, j;
+    out_learnt.copyTo(analyze_toclear);
+    if (ccmin_mode == 2){
+        uint32_t abstract_level = 0;
+        for (i = 1; i < out_learnt.size(); i++)
+            abstract_level |= abstractLevel(var(out_learnt[i])); // (maintain an abstraction of levels involved in conflict)
+
+        for (i = j = 1; i < out_learnt.size(); i++)
+            if (reason(var(out_learnt[i])) == CRef_Undef || !litRedundant(out_learnt[i], abstract_level))
+                out_learnt[j++] = out_learnt[i];
+        
+    }else if (ccmin_mode == 1){
+        for (i = j = 1; i < out_learnt.size(); i++){
+            Var x = var(out_learnt[i]);
+
+            if (reason(x) == CRef_Undef)
+                out_learnt[j++] = out_learnt[i];
+            else{
+                Clause& c = ca[reason(var(out_learnt[i]))];
+                for (int k = c.size() == 2 ? 0 : 1; k < c.size(); k++)
+                    if (!seen[var(c[k])] && level(var(c[k])) > 0){
+                        out_learnt[j++] = out_learnt[i];
+                        break; }
+            }
+        }
+    }else
+        i = j = out_learnt.size();
+
+    max_literals += out_learnt.size();
+    out_learnt.shrink(i - j);
+    tot_literals += out_learnt.size();
+
+    out_lbd = computeLBD(out_learnt);
+    if (out_lbd <= 6 && out_learnt.size() <= 30) // Try further minimization?
+        if (binResMinimize(out_learnt))
+            out_lbd = computeLBD(out_learnt); // Recompute LBD if minimized.
+
+    // Find correct backtrack level:
+    //
+    if (out_learnt.size() == 1)
+        out_btlevel = 0;
+    else{
+        int max_i = 1;
+        // Find the first literal assigned at the next-highest level:
+        for (int i = 2; i < out_learnt.size(); i++)
+            if (level(var(out_learnt[i])) > level(var(out_learnt[max_i])))
+                max_i = i;
+        // Swap-in this literal at index 1:
+        Lit p             = out_learnt[max_i];
+        out_learnt[max_i] = out_learnt[1];
+        out_learnt[1]     = p;
+        out_btlevel       = level(var(p));
+    }
+
+    if (VSIDS){
+        for (int i = 0; i < add_tmp.size(); i++){
+            Var v = var(add_tmp[i]);
+            if (level(v) >= out_btlevel - 1)
+                varBumpActivity(v, 1);
+        }
+        add_tmp.clear();
+    }else{
+        seen[var(p)] = true;
+        for(int i = out_learnt.size() - 1; i >= 0; i--){
+            Var v = var(out_learnt[i]);
+            CRef rea = reason(v);
+            if (rea != CRef_Undef){
+                const Clause& reaC = ca[rea];
+                for (int i = 0; i < reaC.size(); i++){
+                    Lit l = reaC[i];
+                    if (!seen[var(l)]){
+                        seen[var(l)] = true;
+                        almost_conflicted[var(l)]++;
+                        analyze_toclear.push(l); } } } } }
+
+    for (int j = 0; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0;    // ('seen[]' is now cleared)
+}
+
+
+// Try further learnt clause minimization by means of binary clause resolution.
+bool Solver::binResMinimize(vec<Lit>& out_learnt)
+{
+    // Preparation: remember which false variables we have in 'out_learnt'.
+    counter++;
+    for (int i = 1; i < out_learnt.size(); i++)
+        seen2[var(out_learnt[i])] = counter;
+
+    // Get the list of binary clauses containing 'out_learnt[0]'.
+    const vec<Watcher>& ws = watches_bin[~out_learnt[0]];
+
+    int to_remove = 0;
+    for (int i = 0; i < ws.size(); i++){
+        Lit the_other = ws[i].blocker;
+        // Does 'the_other' appear negatively in 'out_learnt'?
+        if (seen2[var(the_other)] == counter && value(the_other) == l_True){
+            to_remove++;
+            seen2[var(the_other)] = counter - 1; // Remember to remove this variable.
+        }
+    }
+
+    // Shrink.
+    if (to_remove > 0){
+        int last = out_learnt.size() - 1;
+        for (int i = 1; i < out_learnt.size() - to_remove; i++)
+            if (seen2[var(out_learnt[i])] != counter)
+                out_learnt[i--] = out_learnt[last--];
+        out_learnt.shrink(to_remove);
+    }
+    return to_remove != 0;
+}
+
+
+// Check if 'p' can be removed. 'abstract_levels' is used to abort early if the algorithm is
+// visiting literals at levels that cannot be removed later.
+bool Solver::litRedundant(Lit p, uint32_t abstract_levels)
+{
+    analyze_stack.clear(); analyze_stack.push(p);
+    int top = analyze_toclear.size();
+    while (analyze_stack.size() > 0){
+        assert(reason(var(analyze_stack.last())) != CRef_Undef);
+        Clause& c = ca[reason(var(analyze_stack.last()))]; analyze_stack.pop();
+
+        // Special handling for binary clauses like in 'analyze()'.
+        if (c.size() == 2 && value(c[0]) == l_False){
+            assert(value(c[1]) == l_True);
+            Lit tmp = c[0];
+            c[0] = c[1], c[1] = tmp; }
+
+        for (int i = 1; i < c.size(); i++){
+            Lit p  = c[i];
+            if (!seen[var(p)] && level(var(p)) > 0){
+                if (reason(var(p)) != CRef_Undef && (abstractLevel(var(p)) & abstract_levels) != 0){
+                    seen[var(p)] = 1;
+                    analyze_stack.push(p);
+                    analyze_toclear.push(p);
+                }else{
+                    for (int j = top; j < analyze_toclear.size(); j++)
+                        seen[var(analyze_toclear[j])] = 0;
+                    analyze_toclear.shrink(analyze_toclear.size() - top);
+                    return false;
+                }
+            }
+        }
+    }
+
+    return true;
+}
+
+
+/*_________________________________________________________________________________________________
+|
+|  analyzeFinal : (p : Lit)  ->  [void]
+|  
+|  Description:
+|    Specialized analysis procedure to express the final conflict in terms of assumptions.
+|    Calculates the (possibly empty) set of assumptions that led to the assignment of 'p', and
+|    stores the result in 'out_conflict'.
+|________________________________________________________________________________________________@*/
+void Solver::analyzeFinal(Lit p, vec<Lit>& out_conflict)
+{
+    out_conflict.clear();
+    out_conflict.push(p);
+
+    if (decisionLevel() == 0)
+        return;
+
+    seen[var(p)] = 1;
+
+    for (int i = trail.size()-1; i >= trail_lim[0]; i--){
+        Var x = var(trail[i]);
+        if (seen[x]){
+            if (reason(x) == CRef_Undef){
+                assert(level(x) > 0);
+                out_conflict.push(~trail[i]);
+            }else{
+                Clause& c = ca[reason(x)];
+                for (int j = c.size() == 2 ? 0 : 1; j < c.size(); j++)
+                    if (level(var(c[j])) > 0)
+                        seen[var(c[j])] = 1;
+            }
+            seen[x] = 0;
+        }
+    }
+
+    seen[var(p)] = 0;
+}
+
+
+void Solver::uncheckedEnqueue(Lit p, CRef from)
+{
+    assert(value(p) == l_Undef);
+    Var x = var(p);
+    if (!VSIDS){
+        picked[x] = conflicts;
+        conflicted[x] = 0;
+        almost_conflicted[x] = 0;
+#ifdef ANTI_EXPLORATION
+        uint32_t age = conflicts - canceled[var(p)];
+        if (age > 0){
+            double decay = pow(0.95, age);
+            activity_CHB[var(p)] *= decay;
+            if (order_heap_CHB.inHeap(var(p)))
+                order_heap_CHB.increase(var(p));
+        }
+#endif
+    }
+
+    assigns[x] = lbool(!sign(p));
+    vardata[x] = mkVarData(from, decisionLevel());
+    trail.push_(p);
+}
+
+
+/*_________________________________________________________________________________________________
+|
+|  propagate : [void]  ->  [Clause*]
+|  
+|  Description:
+|    Propagates all enqueued facts. If a conflict arises, the conflicting clause is returned,
+|    otherwise CRef_Undef.
+|  
+|    Post-conditions:
+|      * the propagation queue is empty, even if there was a conflict.
+|________________________________________________________________________________________________@*/
+CRef Solver::propagate()
+{
+    CRef    confl     = CRef_Undef;
+    int     num_props = 0;
+    watches.cleanAll();
+    watches_bin.cleanAll();
+
+    while (qhead < trail.size()){
+        Lit            p   = trail[qhead++];     // 'p' is enqueued fact to propagate.
+        vec<Watcher>&  ws  = watches[p];
+        Watcher        *i, *j, *end;
+        num_props++;
+
+        vec<Watcher>& ws_bin = watches_bin[p];  // Propagate binary clauses first.
+        for (int k = 0; k < ws_bin.size(); k++){
+            Lit the_other = ws_bin[k].blocker;
+            if (value(the_other) == l_False){
+                confl = ws_bin[k].cref;
+#ifdef LOOSE_PROP_STAT
+                return confl;
+#else
+                goto ExitProp;
+#endif
+            }else if(value(the_other) == l_Undef)
+                uncheckedEnqueue(the_other, ws_bin[k].cref);
+        }
+
+        for (i = j = (Watcher*)ws, end = i + ws.size();  i != end;){
+            // Try to avoid inspecting the clause:
+            Lit blocker = i->blocker;
+            if (value(blocker) == l_True){
+                *j++ = *i++; continue; }
+
+            // Make sure the false literal is data[1]:
+            CRef     cr        = i->cref;
+            Clause&  c         = ca[cr];
+            Lit      false_lit = ~p;
+            if (c[0] == false_lit)
+                c[0] = c[1], c[1] = false_lit;
+            assert(c[1] == false_lit);
+            i++;
+
+            // If 0th watch is true, then clause is already satisfied.
+            Lit     first = c[0];
+            Watcher w     = Watcher(cr, first);
+            if (first != blocker && value(first) == l_True){
+                *j++ = w; continue; }
+
+            // Look for new watch:
+            for (int k = 2; k < c.size(); k++)
+                if (value(c[k]) != l_False){
+                    c[1] = c[k]; c[k] = false_lit;
+                    watches[~c[1]].push(w);
+                    goto NextClause; }
+
+            // Did not find watch -- clause is unit under assignment:
+            *j++ = w;
+            if (value(first) == l_False){
+                confl = cr;
+                qhead = trail.size();
+                // Copy the remaining watches:
+                while (i < end)
+                    *j++ = *i++;
+            }else
+                uncheckedEnqueue(first, cr);
+
+NextClause:;
+        }
+        ws.shrink(i - j);
+    }
+
+ExitProp:;
+    propagations += num_props;
+    simpDB_props -= num_props;
+
+    return confl;
+}
+
+//-----------------------------
+CRef Solver::propagateConfl()
+{
+    CRef    confl     = CRef_Undef;
+    int     num_props = 0;
+    watches.cleanAll();
+    watches_bin.cleanAll();
+
+    while (qhead < trail.size()){
+        Lit            p   = trail[qhead++];     // 'p' is enqueued fact to propagate.
+        vec<Watcher>&  ws  = watches[p];
+        Watcher        *i, *j, *end;
+        num_props++;
+
+        //biary
+        vec<Watcher>& ws_bin = watches_bin[p];  // Propagate binary clauses first.
+        for (int k = 0; k < ws_bin.size(); k++){
+            Lit the_other = ws_bin[k].blocker;
+            if (value(the_other) == l_False){
+                confl = ws_bin[k].cref;
+#ifdef LOOSE_PROP_STAT
+                return confl;
+#else
+                //goto conflExitProp;
+#endif
+            }else if(value(the_other) == l_Undef)
+                uncheckedEnqueue(the_other, ws_bin[k].cref);
+        }
+
+        for (i = j = (Watcher*)ws, end = i + ws.size();  i != end;){
+            // Try to avoid inspecting the clause:
+            Lit blocker = i->blocker;
+            if (value(blocker) == l_True){
+                *j++ = *i++; continue; }
+
+            // Make sure the false literal is data[1]:
+            CRef     cr        = i->cref;
+            Clause&  c         = ca[cr];
+            Lit      false_lit = ~p;
+            if (c[0] == false_lit)
+                c[0] = c[1], c[1] = false_lit;
+            assert(c[1] == false_lit);
+            i++;
+
+            // If 0th watch is true, then clause is already satisfied.
+            Lit     first = c[0];
+            Watcher w     = Watcher(cr, first);
+            if (first != blocker && value(first) == l_True){
+                *j++ = w; continue; }
+
+            // Look for new watch:
+            for (int k = 2; k < c.size(); k++)
+                if (value(c[k]) != l_False){
+                    c[1] = c[k]; c[k] = false_lit;
+                    watches[~c[1]].push(w);
+                    goto conflNextClause; }
+
+            // Did not find watch -- clause is unit under assignment:
+            *j++ = w;
+            if (value(first) == l_False){
+                confl = cr;
+                //qhead = trail.size();
+                // Copy the remaining watches:
+                while (i < end)
+                    *j++ = *i++;
+            }else
+                uncheckedEnqueue(first, cr);
+
+conflNextClause:;
+        }
+        ws.shrink(i - j);
+    }
+
+conflExitProp:;
+    propagations += num_props;
+    simpDB_props -= num_props;
+
+    return confl;
+
+    return confl;
+}
+
+
+//------------------------------------------------
+//cause no effect to origin data struct and give all undef variable a value
+bool Solver::propagateConflSim(){ //cout<<"okin\n";
+    set<Var> undefVars;
+    falseModel.resize(nVars());
+    for(int i=0;i<nVars();i++){
+        if(value(i)==l_Undef){//cout<<"p1\n"; 
+            undefVars.insert((Var)i);//cout<<"p1e\n";
+        }else{// cout<<"p2\n";
+            falseModel[i] = (value(i) == l_True) ? true : false;//cout<<"p2e\n"; 
+        }
+    }
+    //cout<<"ok1\n";
+    vector<Lit> viewList;
+    for(int i=0;i<trail.size();i++) viewList.push_back(trail[i]);
+    int idx = qhead;
+    
+  // cout<<"ok2\n";
+
+
+    while(!undefVars.empty()){
+        while(idx < viewList.size() && !undefVars.empty()){
+            Lit p = viewList[idx++];
+            vec<Watcher>& ws = watches[p];
+            Watcher *i, *j, *end;
+
+            vec<Watcher>& ws_bin = watches_bin[p];
+            for(int k=0;k<ws_bin.size();k++){
+                Lit the_other = ws_bin[k].blocker;
+                if(undefVars.find(var(the_other)) != undefVars.end()){
+                    Var x =var(the_other);
+                    falseModel[x] = (lbool(!sign(the_other))==l_True)?true:false;
+                    viewList.push_back(the_other);
+                    undefVars.erase(x);
+                }
+            }
+            
+            if(undefVars.empty()) break;
+
+            for(i = (Watcher*)ws,end = i+ws.size();i!=end;i++){
+                CRef cr = i->cref;
+                Clause &c = ca[cr];
+                Lit udefLit = c[0];
+                int udefLoc = 0;
+                int udefNum = 0;
+                for(int m=0;m<c.size();m++){
+                    if(undefVars.find(var(c[m]))!= undefVars.end()){
+                        if(udefNum > 0) break;
+                        udefLit = c[m];
+                        udefLoc = m;
+                        udefNum ++;
+                    }
+                }
+                if(udefNum == 1){
+                    Var x =var(udefLit);
+                    falseModel[x] = (lbool(!sign(udefLit))==l_True)?true:false;
+                    viewList.push_back(udefLit);
+                    undefVars.erase(x);
+                }
+            }
+        }
+        if(!undefVars.empty()){
+            Lit choose = mkLit(*(undefVars.begin()),false);
+            Var x =var(choose);
+            falseModel[x] = (lbool(!sign(choose))==l_True)?true:false;
+            viewList.push_back(choose);
+            undefVars.erase(x);
+        }
+    }
+    //cout<<"okout\n";
+    return true;
+}
+
+
+
+
+
+
+//==================================================
+
+
+
+/*_________________________________________________________________________________________________
+|
+|  reduceDB : ()  ->  [void]
+|  
+|  Description:
+|    Remove half of the learnt clauses, minus the clauses locked by the current assignment. Locked
+|    clauses are clauses that are reason to some assignment. Binary clauses are never removed.
+|________________________________________________________________________________________________@*/
+struct reduceDB_lt { 
+    ClauseAllocator& ca;
+    reduceDB_lt(ClauseAllocator& ca_) : ca(ca_) {}
+    bool operator () (CRef x, CRef y) const { return ca[x].activity() < ca[y].activity(); }
+};
+void Solver::reduceDB()
+{
+    int     i, j;
+    //if (local_learnts_dirty) cleanLearnts(learnts_local, LOCAL);
+    //local_learnts_dirty = false;
+
+    sort(learnts_local, reduceDB_lt(ca));
+
+    int limit = learnts_local.size() / 2;
+    for (i = j = 0; i < learnts_local.size(); i++){
+        Clause& c = ca[learnts_local[i]];
+        if (c.mark() == LOCAL)
+            if (c.removable() && !locked(c) && i < limit)
+                removeClause(learnts_local[i]);
+            else{
+                if (!c.removable()) limit++;
+                c.removable(true);
+                learnts_local[j++] = learnts_local[i]; }
+    }
+    learnts_local.shrink(i - j);
+
+    checkGarbage();
+}
+void Solver::reduceDB_Tier2()
+{
+    int i, j;
+    for (i = j = 0; i < learnts_tier2.size(); i++){
+        Clause& c = ca[learnts_tier2[i]];
+        if (c.mark() == TIER2)
+            if (!locked(c) && c.touched() + 30000 < conflicts){
+                learnts_local.push(learnts_tier2[i]);
+                c.mark(LOCAL);
+                //c.removable(true);
+                c.activity() = 0;
+                claBumpActivity(c);
+            }else
+                learnts_tier2[j++] = learnts_tier2[i];
+    }
+    learnts_tier2.shrink(i - j);
+}
+
+
+void Solver::removeSatisfied(vec<CRef>& cs)
+{
+    int i, j;
+    for (i = j = 0; i < cs.size(); i++){
+        Clause& c = ca[cs[i]];
+        if (satisfied(c))
+            removeClause(cs[i]);
+        else
+            cs[j++] = cs[i];
+    }
+    cs.shrink(i - j);
+}
+
+void Solver::safeRemoveSatisfied(vec<CRef>& cs, unsigned valid_mark)
+{
+    int i, j;
+    for (i = j = 0; i < cs.size(); i++){
+        Clause& c = ca[cs[i]];
+        if (c.mark() == valid_mark)
+            if (satisfied(c))
+                removeClause(cs[i]);
+            else
+                cs[j++] = cs[i];
+    }
+    cs.shrink(i - j);
+}
+
+void Solver::rebuildOrderHeap()
+{
+    vec<Var> vs;
+    for (Var v = 0; v < nVars(); v++)
+        if (decision[v] && value(v) == l_Undef)
+            vs.push(v);
+
+    order_heap_CHB  .build(vs);
+    order_heap_VSIDS.build(vs);
+    order_heap_distance.build(vs);
+}
+
+
+/*_________________________________________________________________________________________________
+|
+|  simplify : [void]  ->  [bool]
+|  
+|  Description:
+|    Simplify the clause database according to the current top-level assigment. Currently, the only
+|    thing done here is the removal of satisfied clauses, but more things can be put here.
+|________________________________________________________________________________________________@*/
+bool Solver::simplify()
+{
+    assert(decisionLevel() == 0);
+
+    if (!ok || propagate() != CRef_Undef)
+        return ok = false;
+
+    if (nAssigns() == simpDB_assigns || (simpDB_props > 0))
+        return true;
+
+    // Remove satisfied clauses:
+    removeSatisfied(learnts_core); // Should clean core first.
+    safeRemoveSatisfied(learnts_tier2, TIER2);
+    safeRemoveSatisfied(learnts_local, LOCAL);
+    if (remove_satisfied)        // Can be turned off.
+        removeSatisfied(clauses);
+    checkGarbage();
+    rebuildOrderHeap();
+
+    simpDB_assigns = nAssigns();
+    simpDB_props   = clauses_literals + learnts_literals;   // (shouldn't depend on stats really, but it will do for now)
+
+    return true;
+}
+
+// pathCs[k] is the number of variables assigned at level k,
+// it is initialized to 0 at the begining and reset to 0 after the function execution
+bool Solver::collectFirstUIP(CRef confl){
+    involved_lits.clear();
+    int max_level=1;
+    Clause& c=ca[confl]; int minLevel=decisionLevel();
+    for(int i=0; i<c.size(); i++) {
+        Var v=var(c[i]);
+        //        assert(!seen[v]);
+        if (level(v)>0) {
+            seen[v]=1;
+            var_iLevel_tmp[v]=1;
+            pathCs[level(v)]++;
+            if (minLevel>level(v)) {
+                minLevel=level(v);
+                assert(minLevel>0);
+            }
+            //    varBumpActivity(v);
+        }
+    }
+    int limit=trail_lim[minLevel-1];
+    for(int i=trail.size()-1; i>=limit; i--) {
+        Lit p=trail[i]; Var v=var(p);
+        if (seen[v]) {
+            int currentDecLevel=level(v);
+            //      if (currentDecLevel==decisionLevel())
+            //      	varBumpActivity(v);
+            seen[v]=0;
+            if (--pathCs[currentDecLevel]!=0) {
+                Clause& rc=ca[reason(v)];
+                int reasonVarLevel=var_iLevel_tmp[v]+1;
+                if(reasonVarLevel>max_level) max_level=reasonVarLevel;
+                if (rc.size()==2 && value(rc[0])==l_False) {
+                    // Special case for binary clauses
+                    // The first one has to be SAT
+                    assert(value(rc[1]) != l_False);
+                    Lit tmp = rc[0];
+                    rc[0] =  rc[1], rc[1] = tmp;
+                }
+                for (int j = 1; j < rc.size(); j++){
+                    Lit q = rc[j]; Var v1=var(q);
+                    if (level(v1) > 0) {
+                        if (minLevel>level(v1)) {
+                            minLevel=level(v1); limit=trail_lim[minLevel-1]; 	assert(minLevel>0);
+                        }
+                        if (seen[v1]) {
+                            if (var_iLevel_tmp[v1]<reasonVarLevel)
+                                var_iLevel_tmp[v1]=reasonVarLevel;
+                        }
+                        else {
+                            var_iLevel_tmp[v1]=reasonVarLevel;
+                            //   varBumpActivity(v1);
+                            seen[v1] = 1;
+                            pathCs[level(v1)]++;
+                        }
+                    }
+                }
+            }
+            involved_lits.push(p);
+        }
+    }
+    double inc=var_iLevel_inc;
+    vec<int> level_incs; level_incs.clear();
+    for(int i=0;i<max_level;i++){
+        level_incs.push(inc);
+        inc = inc/my_var_decay;
+    }
+
+    for(int i=0;i<involved_lits.size();i++){
+        Var v =var(involved_lits[i]);
+        //        double old_act=activity_distance[v];
+        //        activity_distance[v] +=var_iLevel_inc * var_iLevel_tmp[v];
+        activity_distance[v]+=var_iLevel_tmp[v]*level_incs[var_iLevel_tmp[v]-1];
+
+        if(activity_distance[v]>1e100){
+            for(int vv=0;vv<nVars();vv++)
+                activity_distance[vv] *= 1e-100;
+            var_iLevel_inc*=1e-100;
+            for(int j=0; j<max_level; j++) level_incs[j]*=1e-100;
+        }
+        if (order_heap_distance.inHeap(v))
+            order_heap_distance.decrease(v);
+
+        //        var_iLevel_inc *= (1 / my_var_decay);
+    }
+    var_iLevel_inc=level_incs[level_incs.size()-1];
+    return true;
+}
+
+struct UIPOrderByILevel_Lt {
+    Solver& solver;
+    const vec<double>&  var_iLevel;
+    bool operator () (Lit x, Lit y) const
+    {
+        return var_iLevel[var(x)] < var_iLevel[var(y)] ||
+                (var_iLevel[var(x)]==var_iLevel[var(y)]&& solver.level(var(x))>solver.level(var(y)));
+    }
+    UIPOrderByILevel_Lt(const vec<double>&  iLevel, Solver& para_solver) : solver(para_solver), var_iLevel(iLevel) { }
+};
+
+CRef Solver::propagateLits(vec<Lit>& lits) {
+    Lit lit;
+    int i;
+
+    for(i=lits.size()-1; i>=0; i--) {
+        lit=lits[i];
+        if (value(lit) == l_Undef) {
+            newDecisionLevel();
+            uncheckedEnqueue(lit);
+            CRef confl = propagate();
+            if (confl != CRef_Undef) {
+                return confl;
+            }
+        }
+    }
+    return CRef_Undef;
+}
+/*_________________________________________________________________________________________________
+|
+|  search : (nof_conflicts : int) (params : const SearchParams&)  ->  [lbool]
+|  
+|  Description:
+|    Search for a model the specified number of conflicts. 
+|  
+|  Output:
+|    'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If
+|    all variables are decision variables, this means that the clause set is satisfiable. 'l_False'
+|    if the clause set is unsatisfiable. 'l_Undef' if the bound on number of conflicts is reached.
+|________________________________________________________________________________________________@*/
+lbool Solver::search(int& nof_conflicts)
+{
+    //--------------------------
+    bool hasnotCalled = true;
+
+    //==========================
+
+
+    assert(ok);
+    int         backtrack_level;
+    int         lbd;
+    vec<Lit>    learnt_clause;
+    bool        cached = false;
+    starts++;
+
+    // simplify
+    //
+    if (conflicts >= curSimplify * nbconfbeforesimplify){
+        //        printf("c ### simplifyAll on conflict : %lld\n", conflicts);
+        //printf("nbClauses: %d, nbLearnts_core: %d, nbLearnts_tier2: %d, nbLearnts_local: %d, nbLearnts: %d\n",
+        //	clauses.size(), learnts_core.size(), learnts_tier2.size(), learnts_local.size(),
+        //	learnts_core.size() + learnts_tier2.size() + learnts_local.size());
+        nbSimplifyAll++;
+        if (!simplifyAll()){
+            return l_False;
+        }
+        curSimplify = (conflicts / nbconfbeforesimplify) + 1;
+        nbconfbeforesimplify += incSimplify;
+    }
+
+    for (;;){
+        //----------------------
+        /*
+        if(cpuTime()>timeLimit){
+            printf("out of Time range!\n");
+            exit(0);
+        }
+        */
+        //======================
+
+
+        CRef confl = propagate();
+
+        if (confl != CRef_Undef){
+            // CONFLICT
+            if (VSIDS){
+                if (--timer == 0 && var_decay < 0.95) timer = 5000, var_decay += 0.01;
+            }else
+                if (step_size > min_step_size) step_size -= step_size_dec;
+
+            conflicts++; nof_conflicts--;
+            if (conflicts == 100000 && learnts_core.size() < 100) core_lbd_cut = 5;
+            if (decisionLevel() == 0) return l_False;
+
+            learnt_clause.clear();
+            if(conflicts>50000) DISTANCE=0;
+            else DISTANCE=1;
+            if(VSIDS && DISTANCE)
+                collectFirstUIP(confl);
+
+            analyze(confl, learnt_clause, backtrack_level, lbd);
+            cancelUntil(backtrack_level);
+
+            lbd--;
+            if (VSIDS){
+                cached = false;
+                conflicts_VSIDS++;
+                lbd_queue.push(lbd);
+                global_lbd_sum += (lbd > 50 ? 50 : lbd); }
+
+            if (learnt_clause.size() == 1){
+                uncheckedEnqueue(learnt_clause[0]);
+            }else{
+                CRef cr = ca.alloc(learnt_clause, true);
+                ca[cr].set_lbd(lbd);
+                if (lbd <= core_lbd_cut){
+                    learnts_core.push(cr);
+                    ca[cr].mark(CORE);
+                }else if (lbd <= 6){
+                    learnts_tier2.push(cr);
+                    ca[cr].mark(TIER2);
+                    ca[cr].touched() = conflicts;
+                }else{
+                    learnts_local.push(cr);
+                    claBumpActivity(ca[cr]); }
+                attachClause(cr);
+                uncheckedEnqueue(learnt_clause[0], cr);
+            }
+            if (drup_file){
+#ifdef BIN_DRUP
+                binDRUP('a', learnt_clause, drup_file);
+#else
+                for (int i = 0; i < learnt_clause.size(); i++)
+                    fprintf(drup_file, "%i ", (var(learnt_clause[i]) + 1) * (-2 * sign(learnt_clause[i]) + 1));
+                fprintf(drup_file, "0\n");
+#endif
+            }
+
+            if (VSIDS) varDecayActivity();
+            claDecayActivity();
+
+            /*if (--learntsize_adjust_cnt == 0){
+                learntsize_adjust_confl *= learntsize_adjust_inc;
+                learntsize_adjust_cnt    = (int)learntsize_adjust_confl;
+                max_learnts             *= learntsize_inc;
+
+                if (verbosity >= 1)
+                    printf("c | %9d | %7d %8d %8d | %8d %8d %6.0f | %6.3f %% |\n",
+                           (int)conflicts,
+                           (int)dec_vars - (trail_lim.size() == 0 ? trail.size() : trail_lim[0]), nClauses(), (int)clauses_literals,
+                           (int)max_learnts, nLearnts(), (double)learnts_literals/nLearnts(), progressEstimate()*100);
+            }*/
+
+        }else{
+            //----------------------------------
+            //delWith ConflPropagation
+            /* old version
+            if(getNowRatio() > conflRatio && nLearnts() > lastLearntNum * areaRatio+1){
+                cout<<"call "<<starts<<"  ";
+                cout<<getNowRatio()<<"\t "<<conflRatio<<"\t "<<lastLearntNum<<"\t "<<nLearnts()<<"\t "<<UnComTime<<"\t "<<cpuTime()-UnComTime<<"\t ";
+                while(true){
+                    CRef confl = propagateConfl();
+                    
+
+                    if(confl == CRef_Undef){
+                        //has no confl,
+                        Lit next = lit_Undef;
+                    
+                        next = pickBranchLit();
+                        if (next == lit_Undef){
+                            
+                            getInitModelByValue();
+                            bool res = this->callUnCom();       cout<<"end\n";
+                            callNum ++;
+                            lastLearntNum = nLearnts();
+
+                            if(res){
+                                solvedByUncom = true;
+                                ok = true;
+                                return l_True;
+                            }else{
+                                cancelUntil(0);
+                                ok = true;
+                                return l_Undef;
+                            }
+                            
+                        }else{
+                            newDecisionLevel();
+                            uncheckedEnqueue(next);
+                    
+                        }
+
+                    }
+
+                }
+            }*/
+            if(hasnotCalled && getNowRatio() > conflRatio && nLearnts() > lastLearntNum * areaRatio+1 && UnComTime < cpuTime()*timeRatio){
+                
+                hasnotCalled = false;
+
+                cout<<"c call "<<starts<<"  ";
+                cout<<getNowRatio()<<"\t "<<conflRatio<<"\t "<<lastLearntNum<<"\t "<<nLearnts()<<"\t "<<UnComTime<<"\t "<<cpuTime()<<"\t ";
+                
+                //construction 
+                double stime = cpuTime();
+                propagateConflSim();
+                bool res = this->callUnCom();
+                double etime = cpuTime();
+                UnComTime += (etime-stime);
+                callNum++;
+                lastLearntNum = nLearnts();
+                
+
+                cout<<"end\n";
+
+                if(res){
+                    solvedByUncom = true;
+                    return l_True;
+                }
+            }
+
+
+            //==================================
+
+
+
+
+            // NO CONFLICT
+            bool restart = false;
+            if (!VSIDS)
+                restart = nof_conflicts <= 0;
+            else if (!cached){
+                restart = lbd_queue.full() && (lbd_queue.avg() * 0.8 > global_lbd_sum / conflicts_VSIDS);
+                cached = true;
+            }
+            if (restart /*|| !withinBudget()*/){
+                lbd_queue.clear();
+                cached = false;
+                // Reached bound on number of conflicts:
+                progress_estimate = progressEstimate();
+                cancelUntil(0);
+                return l_Undef; }
+
+            // Simplify the set of problem clauses:
+            if (decisionLevel() == 0 && !simplify())
+                return l_False;
+
+            if (conflicts >= next_T2_reduce){
+                next_T2_reduce = conflicts + 10000;
+                reduceDB_Tier2(); }
+            if (conflicts >= next_L_reduce){
+                next_L_reduce = conflicts + 15000;
+                reduceDB(); }
+
+            Lit next = lit_Undef;
+            /*while (decisionLevel() < assumptions.size()){
+                // Perform user provided assumption:
+                Lit p = assumptions[decisionLevel()];
+                if (value(p) == l_True){
+                    // Dummy decision level:
+                    newDecisionLevel();
+                }else if (value(p) == l_False){
+                    analyzeFinal(~p, conflict);
+                    return l_False;
+                }else{
+                    next = p;
+                    break;
+                }
+            }
+
+            if (next == lit_Undef)*/{
+                // New variable decision:
+                decisions++;
+                next = pickBranchLit();
+
+                if (next == lit_Undef)
+                    // Model found:
+                    return l_True;
+            }
+
+            // Increase decision level and enqueue 'next'
+            newDecisionLevel();
+            uncheckedEnqueue(next);
+        }
+    }
+}
+
+
+double Solver::progressEstimate() const
+{
+    double  progress = 0;
+    double  F = 1.0 / nVars();
+
+    for (int i = 0; i <= decisionLevel(); i++){
+        int beg = i == 0 ? 0 : trail_lim[i - 1];
+        int end = i == decisionLevel() ? trail.size() : trail_lim[i];
+        progress += pow(F, i) * (end - beg);
+    }
+
+    return progress / nVars();
+}
+
+/*
+  Finite subsequences of the Luby-sequence:
+
+  0: 1
+  1: 1 1 2
+  2: 1 1 2 1 1 2 4
+  3: 1 1 2 1 1 2 4 1 1 2 1 1 2 4 8
+  ...
+
+
+ */
+
+static double luby(double y, int x){
+
+    // Find the finite subsequence that contains index 'x', and the
+    // size of that subsequence:
+    int size, seq;
+    for (size = 1, seq = 0; size < x+1; seq++, size = 2*size+1);
+
+    while (size-1 != x){
+        size = (size-1)>>1;
+        seq--;
+        x = x % size;
+    }
+
+    return pow(y, seq);
+}
+
+static bool switch_mode = false;
+static void SIGALRM_switch(int signum) { switch_mode = true; }
+
+// NOTE: assumptions passed in member-variable 'assumptions'.
+lbool Solver::solve_()
+{
+    double switchMode = opt_switchMode;
+
+    signal(SIGALRM, SIGALRM_switch);
+    alarm(switchMode);
+
+    model.clear();
+    conflict.clear();
+    if (!ok) return l_False;
+
+    solves++;
+
+    max_learnts               = nClauses() * learntsize_factor;
+    learntsize_adjust_confl   = learntsize_adjust_start_confl;
+    learntsize_adjust_cnt     = (int)learntsize_adjust_confl;
+    lbool   status            = l_Undef;
+
+    if (verbosity >= 1){
+        printf("c ============================[ ReasonLS Maple_LD ]==============================\n");
+        //printf("c | Conflicts |          ORIGINAL         |          LEARNT          | Progress |\n");
+        //printf("c |           |    Vars  Clauses Literals |    Limit  Clauses Lit/Cl |          |\n");
+        printf("c areaRatio:%lf         conflRatio:%lf          timeRatio:%lf\n",areaRatio,conflRatio,timeRatio);
+        printf("c maxFlipRatio:%lf    initFlipRatio:%lf     raiseFlipRatio:%lf\t \n",maxflipRatio,lastflipRatio,raiseFlipRatio);
+        printf("c -------------------------------------------------------------------------------\n");
+        printf("c call|nRestart|trueRatio|expect|LastLearnts|Learnts|ccnrTime |totalTime |  end\n");       
+        printf("c ===============================================================================\n");
+                // c ===============================================================================
+                // c call 289  0.900706     0.9     0       22857   0       4.04946         end
+                // c call 387  0.906502     0.9     22857   43020   3.70781         10.7654         end
+                // c ===============================================================================
+    }
+
+     //-----------------
+    lastLearntNum = nLearnts();
+    //=================
+
+
+    add_tmp.clear();
+
+    VSIDS = true;
+    int init = 10000;
+    while (status == l_Undef && init > 0 /*&& withinBudget()*/)
+        status = search(init);
+    VSIDS = false;
+
+    // Search:
+    int curr_restarts = 0;
+    while (status == l_Undef /*&& withinBudget()*/){
+        if (VSIDS){
+            int weighted = INT32_MAX;
+            status = search(weighted);
+        }else{
+            int nof_conflicts = luby(restart_inc, curr_restarts) * restart_first;
+            curr_restarts++;
+            status = search(nof_conflicts);
+        }
+        if (!VSIDS && switch_mode){
+            VSIDS = true;
+            printf("c Switched to VSIDS.\n");
+            fflush(stdout);
+            picked.clear();
+            conflicted.clear();
+            almost_conflicted.clear();
+#ifdef ANTI_EXPLORATION
+            canceled.clear();
+#endif
+        }
+    }
+
+    if (verbosity >= 1)
+        printf("c ===============================================================================\n");
+
+#ifdef BIN_DRUP
+    if (drup_file && status == l_False) binDRUP_flush(drup_file);
+#endif
+
+    if (status == l_True){
+        // Extend & copy model:
+        model.growTo(nVars());
+         //------------------------------------------------------------------------------------------------
+        for (int i = 0; i < nVars(); i++) solvedByUncom ? model[i] = result_call[i] :model[i] = value(i);
+        //================================================================================================
+    }else if (status == l_False && conflict.size() == 0)
+        ok = false;
+
+    cancelUntil(0);
+    return status;
+}
+
+//=================================================================================================
+// Writing CNF to DIMACS:
+// 
+// FIXME: this needs to be rewritten completely.
+
+static Var mapVar(Var x, vec<Var>& map, Var& max)
+{
+    if (map.size() <= x || map[x] == -1){
+        map.growTo(x+1, -1);
+        map[x] = max++;
+    }
+    return map[x];
+}
+
+
+void Solver::toDimacs(FILE* f, Clause& c, vec<Var>& map, Var& max)
+{
+    if (satisfied(c)) return;
+
+    for (int i = 0; i < c.size(); i++)
+        if (value(c[i]) != l_False)
+            fprintf(f, "%s%d ", sign(c[i]) ? "-" : "", mapVar(var(c[i]), map, max)+1);
+    fprintf(f, "0\n");
+}
+
+
+void Solver::toDimacs(const char *file, const vec<Lit>& assumps)
+{
+    FILE* f = fopen(file, "wr");
+    if (f == NULL)
+        fprintf(stderr, "could not open file %s\n", file), exit(1);
+    toDimacs(f, assumps);
+    fclose(f);
+}
+
+
+void Solver::toDimacs(FILE* f, const vec<Lit>& assumps)
+{
+    // Handle case when solver is in contradictory state:
+    if (!ok){
+        fprintf(f, "p cnf 1 2\n1 0\n-1 0\n");
+        return; }
+
+    vec<Var> map; Var max = 0;
+
+    // Cannot use removeClauses here because it is not safe
+    // to deallocate them at this point. Could be improved.
+    int cnt = 0;
+    for (int i = 0; i < clauses.size(); i++)
+        if (!satisfied(ca[clauses[i]]))
+            cnt++;
+
+    for (int i = 0; i < clauses.size(); i++)
+        if (!satisfied(ca[clauses[i]])){
+            Clause& c = ca[clauses[i]];
+            for (int j = 0; j < c.size(); j++)
+                if (value(c[j]) != l_False)
+                    mapVar(var(c[j]), map, max);
+        }
+
+    // Assumptions are added as unit clauses:
+    cnt += assumptions.size();
+
+    fprintf(f, "p cnf %d %d\n", max, cnt);
+
+    for (int i = 0; i < assumptions.size(); i++){
+        assert(value(assumptions[i]) != l_False);
+        fprintf(f, "%s%d 0\n", sign(assumptions[i]) ? "-" : "", mapVar(var(assumptions[i]), map, max)+1);
+    }
+
+    for (int i = 0; i < clauses.size(); i++)
+        toDimacs(f, ca[clauses[i]], map, max);
+
+    if (verbosity > 0)
+        printf("c Wrote %d clauses with %d variables.\n", cnt, max);
+}
+
+
+//=================================================================================================
+// Garbage Collection methods:
+
+void Solver::relocAll(ClauseAllocator& to)
+{
+    // All watchers:
+    //
+    // for (int i = 0; i < watches.size(); i++)
+    watches.cleanAll();
+    watches_bin.cleanAll();
+    for (int v = 0; v < nVars(); v++)
+        for (int s = 0; s < 2; s++){
+            Lit p = mkLit(v, s);
+            // printf(" >>> RELOCING: %s%d\n", sign(p)?"-":"", var(p)+1);
+            vec<Watcher>& ws = watches[p];
+            for (int j = 0; j < ws.size(); j++)
+                ca.reloc(ws[j].cref, to);
+            vec<Watcher>& ws_bin = watches_bin[p];
+            for (int j = 0; j < ws_bin.size(); j++)
+                ca.reloc(ws_bin[j].cref, to);
+        }
+
+    // All reasons:
+    //
+    for (int i = 0; i < trail.size(); i++){
+        Var v = var(trail[i]);
+
+        if (reason(v) != CRef_Undef && (ca[reason(v)].reloced() || locked(ca[reason(v)])))
+            ca.reloc(vardata[v].reason, to);
+    }
+
+    // All learnt:
+    //
+    for (int i = 0; i < learnts_core.size(); i++)
+        ca.reloc(learnts_core[i], to);
+    for (int i = 0; i < learnts_tier2.size(); i++)
+        ca.reloc(learnts_tier2[i], to);
+    for (int i = 0; i < learnts_local.size(); i++)
+        ca.reloc(learnts_local[i], to);
+
+    // All original:
+    //
+    int i, j;
+    for (i = j = 0; i < clauses.size(); i++)
+        if (ca[clauses[i]].mark() != 1){
+            ca.reloc(clauses[i], to);
+            clauses[j++] = clauses[i]; }
+    clauses.shrink(i - j);
+}
+
+
+void Solver::garbageCollect()
+{
+    // Initialize the next region to a size corresponding to the estimated utilization degree. This
+    // is not precise but should avoid some unnecessary reallocations for the new region:
+    ClauseAllocator to(ca.size() - ca.wasted());
+
+    relocAll(to);
+    if (verbosity >= 2)
+        printf("c |  Garbage collection:   %12d bytes => %12d bytes             |\n",
+               ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size);
+    to.moveTo(ca);
+}
+
+
+//-------------------------------------------------------
+
+//--------------------------------------------
+
+
+
+void Solver::getInitModelByValue(){
+    falseModel.clear();
+    for(int i=0;i<nVars();i++){
+        if(value(i)==l_False){
+            falseModel.push_back(false);
+        }else{
+            falseModel.push_back(true);
+        }
+    }
+}
+
+/*
+bool Solver::callUnCom(){
+       
+    ls_solver ccnr;
+    
+    int	ret = build_instance(ccnr);
+
+    if (!ret) { printf("c init fail\n");return 1;}
+
+    vector<bool> * vp = & falseModel;  
+    
+    long long nowstep = (long long ) nVars()*lastflipRatio;
+    ccnr._max_steps = min(nowstep, maxstep);
+    lastflipRatio *= raiseFlipRatio;
+
+    if(ccnr.local_search(vp)){
+        
+        //ccnr.print_solution();
+        result_call.clear();
+        for (int v=1; v <= ccnr._num_vars; v++)
+        {
+            if (ccnr._solution[v]==0) result_call.push_back(l_False);
+            else result_call.push_back(l_True);
+        }
+
+        return true;
+    }else{
+        //UnComTime+=get_runtime();
+        return false;
+    }
+
+}
+*/
+
+
+
+
+bool Solver::callUnCom(){
+       
+    ls_solver ccnr;
+    
+    int	ret = build_instance(ccnr);
+
+    if (!ret) { printf("c init fail\n");return 1;}
+
+    if(timeRatio <= 1){
+        //Normal Call
+        vector<bool> * vp = & falseModel;  
+        
+        long long nowstep = (long long ) nVars()*lastflipRatio;
+        ccnr._max_steps = min(nowstep, maxstep);
+        lastflipRatio *= raiseFlipRatio;
+
+        if(ccnr.local_search(vp)){
+            
+            //ccnr.print_solution();
+            result_call.clear();
+            for (int v=1; v <= ccnr._num_vars; v++)
+            {
+                if (ccnr._solution[v]==0) result_call.push_back(l_False);
+                else result_call.push_back(l_True);
+            }
+
+            return true;
+        }else{
+            //UnComTime+=get_runtime();
+            return false;
+        }
+    }else{
+
+        //largely increase call time of cnnr
+        ccnr._max_steps = maxstep;
+        ccnr._max_tries = 10;
+        if(ccnr.local_search()){
+
+            //ccnr.print_solution();
+            result_call.clear();
+            for (int v=1; v <= ccnr._num_vars; v++)
+            {
+                if (ccnr._solution[v]==0) result_call.push_back(l_False);
+                else result_call.push_back(l_True);
+            }
+
+            return true;
+        }else{
+            //UnComTime+=get_runtime();
+            return false;
+        }
+        
+    }
+}
+
+
+
+
+bool Solver::build_instance(ls_solver &ls_s){
+    int ct,i,j,v;
+    int cur_lit;
+    vector<int> temp_clause;
+    ls_s._num_vars = nVars();
+    ls_s._num_clauses = nClauses()+nLearnts()+((trail_lim.size()>0)? trail_lim[0] : 0);
+    //cout<<ls_s._num_vars<<" "<<ls_s._num_clauses<<endl;
+    if(!ls_s.make_space()) return false;
+
+    //read clauses, each at a time
+    ct = 0;
+    //clause ctmp;
+    for(int md=0;md<4;md++){
+        vec<CRef> &vs = (md==0)?clauses:(md==1?learnts_core:(md==2?learnts_tier2:learnts_local));
+        for(i=0;i<vs.size();i++){
+            //ls_s._clauses.push_back(ctmp);
+            temp_clause.clear();
+            CRef &cr = vs[i];
+            Clause &c = ca[cr];
+            vector<int>().swap(temp_clause);
+            for(j=0;j<c.size();j++){
+                cur_lit = toFormal(c[j]);
+                temp_clause.push_back(cur_lit);
+            }
+            for(int item:temp_clause){
+                ls_s._clauses[ct].literals.push_back(lit(item,ct));
+            }
+            ct++;
+        }
+    }
+    if(trail_lim.size() >0 ){
+        for(i=0;i<trail_lim[0];i++){
+            //ls_s._clauses.push_back(ctmp);
+            ls_s._clauses[ct].literals.push_back(lit(toFormal(trail[i]),ct));
+            ct++;
+        }
+    }
+    for (int c=0; c < ls_s._num_clauses; c++) 
+    {
+        for(lit item: ls_s._clauses[c].literals)
+        {
+            v = item.var_num;
+            ls_s._vars[v].literals.push_back(item);
+        }
+    }
+    ls_s.build_neighborhood();
+    return true;
+}

+ 598 - 0
sources/core/Solver.h

@@ -0,0 +1,598 @@
+/****************************************************************************************[Solver.h]
+MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+           Copyright (c) 2007-2010, Niklas Sorensson
+
+Chanseok Oh's MiniSat Patch Series -- Copyright (c) 2015, Chanseok Oh
+ 
+Maple_LCM, Based on MapleCOMSPS_DRUP -- Copyright (c) 2017, Mao Luo, Chu-Min LI, Fan Xiao: implementing a learnt clause minimisation approach
+Reference: M. Luo, C.-M. Li, F. Xiao, F. Manya, and Z. L. , “An effective learnt clause minimization approach for cdcl sat solvers,” in IJCAI-2017, 2017, pp. to–appear.
+ 
+Maple_LCM_Dist, Based on Maple_LCM -- Copyright (c) 2017, Fan Xiao, Chu-Min LI, Mao Luo: using a new branching heuristic called Distance at the beginning of search
+ 
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_Solver_h
+#define Minisat_Solver_h
+
+#define ANTI_EXPLORATION
+#define BIN_DRUP
+
+#define GLUCOSE23
+//#define INT_QUEUE_AVG
+//#define LOOSE_PROP_STAT
+
+#ifdef GLUCOSE23
+#define INT_QUEUE_AVG
+#define LOOSE_PROP_STAT
+#endif
+
+#include "mtl/Vec.h"
+#include "mtl/Heap.h"
+#include "mtl/Alg.h"
+#include "utils/Options.h"
+#include "core/SolverTypes.h"
+#include "utils/ccnr.h"
+#include "utils/System.h"
+#include <vector>
+#include <set>
+
+// Don't change the actual numbers.
+#define LOCAL 0
+#define TIER2 2
+#define CORE  3
+
+namespace Minisat {
+
+//=================================================================================================
+// Solver -- the main class:
+
+class Solver {
+private:
+    template<typename T>
+    class MyQueue {
+        int max_sz, q_sz;
+        int ptr;
+        int64_t sum;
+        vec<T> q;
+    public:
+        MyQueue(int sz) : max_sz(sz), q_sz(0), ptr(0), sum(0) { assert(sz > 0); q.growTo(sz); }
+        inline bool   full () const { return q_sz == max_sz; }
+#ifdef INT_QUEUE_AVG
+        inline T      avg  () const { assert(full()); return sum / max_sz; }
+#else
+        inline double avg  () const { assert(full()); return sum / (double) max_sz; }
+#endif
+        inline void   clear()       { sum = 0; q_sz = 0; ptr = 0; }
+        void push(T e) {
+            if (q_sz < max_sz) q_sz++;
+            else sum -= q[ptr];
+            sum += e;
+            q[ptr++] = e;
+            if (ptr == max_sz) ptr = 0;
+        }
+    };
+
+public:
+
+    // Constructor/Destructor:
+    //
+    Solver();
+    virtual ~Solver();
+
+    // Problem specification:
+    //
+    Var     newVar    (bool polarity = true, bool dvar = true); // Add a new variable with parameters specifying variable mode.
+
+    bool    addClause (const vec<Lit>& ps);                     // Add a clause to the solver.
+    bool    addEmptyClause();                                   // Add the empty clause, making the solver contradictory.
+    bool    addClause (Lit p);                                  // Add a unit clause to the solver.
+    bool    addClause (Lit p, Lit q);                           // Add a binary clause to the solver.
+    bool    addClause (Lit p, Lit q, Lit r);                    // Add a ternary clause to the solver.
+    bool    addClause_(      vec<Lit>& ps);                     // Add a clause to the solver without making superflous internal copy. Will
+    // change the passed vector 'ps'.
+
+    // Solving:
+    //
+    bool    simplify     ();                        // Removes already satisfied clauses.
+    bool    solve        (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions.
+    lbool   solveLimited (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions (With resource constraints).
+    bool    solve        ();                        // Search without assumptions.
+    bool    solve        (Lit p);                   // Search for a model that respects a single assumption.
+    bool    solve        (Lit p, Lit q);            // Search for a model that respects two assumptions.
+    bool    solve        (Lit p, Lit q, Lit r);     // Search for a model that respects three assumptions.
+    bool    okay         () const;                  // FALSE means solver is in a conflicting state
+
+    void    toDimacs     (FILE* f, const vec<Lit>& assumps);            // Write CNF to file in DIMACS-format.
+    void    toDimacs     (const char *file, const vec<Lit>& assumps);
+    void    toDimacs     (FILE* f, Clause& c, vec<Var>& map, Var& max);
+
+    // Convenience versions of 'toDimacs()':
+    void    toDimacs     (const char* file);
+    void    toDimacs     (const char* file, Lit p);
+    void    toDimacs     (const char* file, Lit p, Lit q);
+    void    toDimacs     (const char* file, Lit p, Lit q, Lit r);
+    
+    // Variable mode:
+    //
+    void    setPolarity    (Var v, bool b); // Declare which polarity the decision heuristic should use for a variable. Requires mode 'polarity_user'.
+    void    setDecisionVar (Var v, bool b); // Declare if a variable should be eligible for selection in the decision heuristic.
+
+    // Read state:
+    //
+    lbool   value      (Var x) const;       // The current value of a variable.
+    lbool   value      (Lit p) const;       // The current value of a literal.
+    lbool   modelValue (Var x) const;       // The value of a variable in the last model. The last call to solve must have been satisfiable.
+    lbool   modelValue (Lit p) const;       // The value of a literal in the last model. The last call to solve must have been satisfiable.
+    int     nAssigns   ()      const;       // The current number of assigned literals.
+    int     nClauses   ()      const;       // The current number of original clauses.
+    int     nLearnts   ()      const;       // The current number of learnt clauses.
+    int     nVars      ()      const;       // The current number of variables.
+    int     nFreeVars  ()      const;
+
+    // Resource contraints:
+    //
+    void    setConfBudget(int64_t x);
+    void    setPropBudget(int64_t x);
+    void    budgetOff();
+    void    interrupt();          // Trigger a (potentially asynchronous) interruption of the solver.
+    void    clearInterrupt();     // Clear interrupt indicator flag.
+
+    // Memory managment:
+    //
+    virtual void garbageCollect();
+    void    checkGarbage(double gf);
+    void    checkGarbage();
+
+    // Extra results: (read-only member variable)
+    //
+    vec<lbool> model;             // If problem is satisfiable, this vector contains the model (if any).
+    vec<Lit>   conflict;          // If problem is unsatisfiable (possibly under assumptions),
+    // this vector represent the final conflict clause expressed in the assumptions.
+
+    // Mode of operation:
+    //
+    FILE*     drup_file;
+    int       verbosity;
+    double    step_size;
+    double    step_size_dec;
+    double    min_step_size;
+    int       timer;
+    double    var_decay;
+    double    clause_decay;
+    double    random_var_freq;
+    double    random_seed;
+    bool      VSIDS;
+    int       ccmin_mode;         // Controls conflict clause minimization (0=none, 1=basic, 2=deep).
+    int       phase_saving;       // Controls the level of phase saving (0=none, 1=limited, 2=full).
+    bool      rnd_pol;            // Use random polarities for branching heuristics.
+    bool      rnd_init_act;       // Initialize variable activities with a small random value.
+    double    garbage_frac;       // The fraction of wasted memory allowed before a garbage collection is triggered.
+
+    int       restart_first;      // The initial restart limit.                                                                (default 100)
+    double    restart_inc;        // The factor with which the restart limit is multiplied in each restart.                    (default 1.5)
+    double    learntsize_factor;  // The intitial limit for learnt clauses is a factor of the original clauses.                (default 1 / 3)
+    double    learntsize_inc;     // The limit for learnt clauses is multiplied with this factor each restart.                 (default 1.1)
+
+    int       learntsize_adjust_start_confl;
+    double    learntsize_adjust_inc;
+
+    // Statistics: (read-only member variable)
+    //
+    uint64_t solves, starts, decisions, rnd_decisions, propagations, conflicts, conflicts_VSIDS;
+    uint64_t dec_vars, clauses_literals, learnts_literals, max_literals, tot_literals;
+
+    vec<uint32_t> picked;
+    vec<uint32_t> conflicted;
+    vec<uint32_t> almost_conflicted;
+#ifdef ANTI_EXPLORATION
+    vec<uint32_t> canceled;
+#endif
+
+protected:
+
+    // Helper structures:
+    //
+    struct VarData { CRef reason; int level; };
+    static inline VarData mkVarData(CRef cr, int l){ VarData d = {cr, l}; return d; }
+
+    struct Watcher {
+        CRef cref;
+        Lit  blocker;
+        Watcher(CRef cr, Lit p) : cref(cr), blocker(p) {}
+        bool operator==(const Watcher& w) const { return cref == w.cref; }
+        bool operator!=(const Watcher& w) const { return cref != w.cref; }
+    };
+
+    struct WatcherDeleted
+    {
+        const ClauseAllocator& ca;
+        WatcherDeleted(const ClauseAllocator& _ca) : ca(_ca) {}
+        bool operator()(const Watcher& w) const { return ca[w.cref].mark() == 1; }
+    };
+
+    struct VarOrderLt {
+        const vec<double>&  activity;
+        bool operator () (Var x, Var y) const { return activity[x] > activity[y]; }
+        VarOrderLt(const vec<double>&  act) : activity(act) { }
+    };
+
+    // Solver state:
+    //
+    bool                ok;               // If FALSE, the constraints are already unsatisfiable. No part of the solver state may be used!
+    vec<CRef>           clauses;          // List of problem clauses.
+    vec<CRef>           learnts_core,     // List of learnt clauses.
+    learnts_tier2,
+    learnts_local;
+    double              cla_inc;          // Amount to bump next clause with.
+    vec<double>         activity_CHB,     // A heuristic measurement of the activity of a variable.
+    activity_VSIDS,activity_distance;
+    double              var_inc;          // Amount to bump next variable with.
+    OccLists<Lit, vec<Watcher>, WatcherDeleted>
+    watches_bin,      // Watches for binary clauses only.
+    watches;          // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true).
+    vec<lbool>          assigns;          // The current assignments.
+    vec<char>           polarity;         // The preferred polarity of each variable.
+    vec<char>           decision;         // Declares if a variable is eligible for selection in the decision heuristic.
+    vec<Lit>            trail;            // Assignment stack; stores all assigments made in the order they were made.
+    vec<int>            trail_lim;        // Separator indices for different decision levels in 'trail'.
+    vec<VarData>        vardata;          // Stores reason and level for each variable.
+    int                 qhead;            // Head of queue (as index into the trail -- no more explicit propagation queue in MiniSat).
+    int                 simpDB_assigns;   // Number of top-level assignments since last execution of 'simplify()'.
+    int64_t             simpDB_props;     // Remaining number of propagations that must be made before next execution of 'simplify()'.
+    vec<Lit>            assumptions;      // Current set of assumptions provided to solve by the user.
+    Heap<VarOrderLt>    order_heap_CHB,   // A priority queue of variables ordered with respect to the variable activity.
+    order_heap_VSIDS,order_heap_distance;
+    double              progress_estimate;// Set by 'search()'.
+    bool                remove_satisfied; // Indicates whether possibly inefficient linear scan for satisfied clauses should be performed in 'simplify'.
+
+    int                 core_lbd_cut;
+    float               global_lbd_sum;
+    MyQueue<int>        lbd_queue;  // For computing moving averages of recent LBD values.
+
+    uint64_t            next_T2_reduce,
+    next_L_reduce;
+
+    ClauseAllocator     ca;
+
+    // Temporaries (to reduce allocation overhead). Each variable is prefixed by the method in which it is
+    // used, exept 'seen' wich is used in several places.
+    //
+    vec<char>           seen;
+    vec<Lit>            analyze_stack;
+    vec<Lit>            analyze_toclear;
+    vec<Lit>            add_tmp;
+    vec<Lit>            add_oc;
+
+    vec<uint64_t>       seen2;    // Mostly for efficient LBD computation. 'seen2[i]' will indicate if decision level or variable 'i' has been seen.
+    uint64_t            counter;  // Simple counter for marking purpose with 'seen2'.
+
+    double              max_learnts;
+    double              learntsize_adjust_confl;
+    int                 learntsize_adjust_cnt;
+
+    // Resource contraints:
+    //
+    int64_t             conflict_budget;    // -1 means no budget.
+    int64_t             propagation_budget; // -1 means no budget.
+    bool                asynch_interrupt;
+
+    // Main internal methods:
+    //
+    void     insertVarOrder   (Var x);                                                 // Insert a variable in the decision order priority queue.
+    Lit      pickBranchLit    ();                                                      // Return the next decision variable.
+    void     newDecisionLevel ();                                                      // Begins a new decision level.
+    void     uncheckedEnqueue (Lit p, CRef from = CRef_Undef);                         // Enqueue a literal. Assumes value of literal is undefined.
+    bool     enqueue          (Lit p, CRef from = CRef_Undef);                         // Test if fact 'p' contradicts current state, enqueue otherwise.
+    CRef     propagate        ();                                                      // Perform unit propagation. Returns possibly conflicting clause.
+    CRef     propagateConfl   ();
+    bool     propagateConflSim();
+    void     cancelUntil      (int level);                                             // Backtrack until a certain level.
+    void     analyze          (CRef confl, vec<Lit>& out_learnt, int& out_btlevel, int& out_lbd);    // (bt = backtrack)
+    void     analyzeFinal     (Lit p, vec<Lit>& out_conflict);                         // COULD THIS BE IMPLEMENTED BY THE ORDINARIY "analyze" BY SOME REASONABLE GENERALIZATION?
+    bool     litRedundant     (Lit p, uint32_t abstract_levels);                       // (helper method for 'analyze()')
+    lbool    search           (int& nof_conflicts);                                    // Search for a given number of conflicts.
+    lbool    solve_           ();                                                      // Main solve method (assumptions given in 'assumptions').
+    void     reduceDB         ();                                                      // Reduce the set of learnt clauses.
+    void     reduceDB_Tier2   ();
+    void     removeSatisfied  (vec<CRef>& cs);                                         // Shrink 'cs' to contain only non-satisfied clauses.
+    void     safeRemoveSatisfied(vec<CRef>& cs, unsigned valid_mark);
+    void     rebuildOrderHeap ();
+    bool     binResMinimize   (vec<Lit>& out_learnt);                                  // Further learnt clause minimization by binary resolution.
+
+    // Maintaining Variable/Clause activity:
+    //
+    void     varDecayActivity ();                      // Decay all variables with the specified factor. Implemented by increasing the 'bump' value instead.
+    void     varBumpActivity  (Var v, double mult);    // Increase a variable with the current 'bump' value.
+    void     claDecayActivity ();                      // Decay all clauses with the specified factor. Implemented by increasing the 'bump' value instead.
+    void     claBumpActivity  (Clause& c);             // Increase a clause with the current 'bump' value.
+
+    // Operations on clauses:
+    //
+    void     attachClause     (CRef cr);               // Attach a clause to watcher lists.
+    void     detachClause     (CRef cr, bool strict = false); // Detach a clause to watcher lists.
+    void     removeClause     (CRef cr);               // Detach and free a clause.
+    bool     locked           (const Clause& c) const; // Returns TRUE if a clause is a reason for some implication in the current state.
+    bool     satisfied        (const Clause& c) const; // Returns TRUE if a clause is satisfied in the current state.
+
+    void     relocAll         (ClauseAllocator& to);
+
+    // Misc:
+    //
+    int      decisionLevel    ()      const; // Gives the current decisionlevel.
+    uint32_t abstractLevel    (Var x) const; // Used to represent an abstraction of sets of decision levels.
+    CRef     reason           (Var x) const;
+public:
+    int      level            (Var x) const;
+protected:
+    double   progressEstimate ()      const; // DELETE THIS ?? IT'S NOT VERY USEFUL ...
+    bool     withinBudget     ()      const;
+
+    template<class V> int computeLBD(const V& c) {
+        int lbd = 0;
+
+        counter++;
+        for (int i = 0; i < c.size(); i++){
+            int l = level(var(c[i]));
+            if (l != 0 && seen2[l] != counter){
+                seen2[l] = counter;
+                lbd++; } }
+
+        return lbd;
+    }
+
+#ifdef BIN_DRUP
+    static int buf_len;
+    static unsigned char drup_buf[];
+    static unsigned char* buf_ptr;
+
+    static inline void byteDRUP(Lit l){
+        unsigned int u = 2 * (var(l) + 1) + sign(l);
+        do{
+            *buf_ptr++ = u & 0x7f | 0x80; buf_len++;
+            u = u >> 7;
+        }while (u);
+        *(buf_ptr - 1) &= 0x7f; // End marker of this unsigned number.
+    }
+
+    template<class V>
+    static inline void binDRUP(unsigned char op, const V& c, FILE* drup_file){
+        assert(op == 'a' || op == 'd');
+        *buf_ptr++ = op; buf_len++;
+        for (int i = 0; i < c.size(); i++) byteDRUP(c[i]);
+        *buf_ptr++ = 0; buf_len++;
+        if (buf_len > 1048576) binDRUP_flush(drup_file);
+    }
+
+    static inline void binDRUP_strengthen(const Clause& c, Lit l, FILE* drup_file){
+        *buf_ptr++ = 'a'; buf_len++;
+        for (int i = 0; i < c.size(); i++)
+            if (c[i] != l) byteDRUP(c[i]);
+        *buf_ptr++ = 0; buf_len++;
+        if (buf_len > 1048576) binDRUP_flush(drup_file);
+    }
+
+    static inline void binDRUP_flush(FILE* drup_file){
+//        fwrite(drup_buf, sizeof(unsigned char), buf_len, drup_file);
+        fwrite_unlocked(drup_buf, sizeof(unsigned char), buf_len, drup_file);
+        buf_ptr = drup_buf; buf_len = 0;
+    }
+#endif
+
+    // Static helpers:
+    //
+
+    // Returns a random float 0 <= x < 1. Seed must never be 0.
+    static inline double drand(double& seed) {
+        seed *= 1389796;
+        int q = (int)(seed / 2147483647);
+        seed -= (double)q * 2147483647;
+        return seed / 2147483647; }
+
+    // Returns a random integer 0 <= x < size. Seed must never be 0.
+    static inline int irand(double& seed, int size) {
+        return (int)(drand(seed) * size); }
+
+
+    // simplify
+    //
+public:
+    bool	simplifyAll();
+    void	simplifyLearnt(Clause& c);
+    bool	simplifyLearnt_x(vec<CRef>& learnts_x);
+    bool	simplifyLearnt_core();
+    bool	simplifyLearnt_tier2();
+    int		trailRecord;
+    void	litsEnqueue(int cutP, Clause& c);
+    void	cancelUntilTrailRecord();
+    void	simpleUncheckEnqueue(Lit p, CRef from = CRef_Undef);
+    CRef    simplePropagate();
+    uint64_t nbSimplifyAll;
+    uint64_t simplified_length_record, original_length_record;
+    uint64_t s_propagations;
+
+    vec<Lit> simp_learnt_clause;
+    vec<CRef> simp_reason_clause;
+    void	simpleAnalyze(CRef confl, vec<Lit>& out_learnt, vec<CRef>& reason_clause, bool True_confl);
+
+    // in redundant
+    bool removed(CRef cr);
+    // adjust simplifyAll occasion
+    long curSimplify;
+    int nbconfbeforesimplify;
+    int incSimplify;
+
+    bool collectFirstUIP(CRef confl);
+    vec<double> var_iLevel,var_iLevel_tmp;
+    uint64_t nbcollectfirstuip, nblearntclause, nbDoubleConflicts, nbTripleConflicts;
+    int uip1, uip2;
+    vec<int> pathCs;
+    CRef propagateLits(vec<Lit>& lits);
+    uint64_t previousStarts;
+    double var_iLevel_inc;
+    vec<Lit> involved_lits;
+    double    my_var_decay;
+    bool   DISTANCE;
+
+
+public:
+
+
+    //-------------------
+    vector<lbool>   result_call;
+    vector<bool>    falseModel;
+
+    float conflRatio           ;// = 0.90;         //比率,当大于这个量的时候,ok均为true,并忽略所有的错误,一直搜到底
+    float areaRatio            ;// = 1.01;        //用来限制生成的新的不完备解不与上一次的解搜索空间太近
+    long long maxstep          ;// = 20000000;     //2kw 取maxstep 和 maxflipRatio之间最小的数作为上界
+    float maxflipRatio         ;// = 600.0;        //不完备算法中反转次数和变量之间的比率
+    float lastflipRatio        ;// = 100.0;         //初始比率
+    float raiseFlipRatio       ;// = 1.02;         //每次将反转次数提高的比例
+    //double timeLimit            = 999999.0;      //程序超过这个时间就会退出
+    double timeRatio           ;// = 0.35;          //不完备算法求解时间最高占整体求解时间的比例
+
+    double  UnComTime          ;// = 0.0;
+    int     callNum            ;// = 0;
+    bool    solvedByUncom      ;// = false;
+    bool    forceRestart       ;// = false;
+    int     lastLearntNum      ;// = 0;
+    //;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+    
+    void getInitModelByValue();
+
+    bool callUnCom();
+
+    bool build_instance(ls_solver &ls_s);
+
+    inline double getNowRatio(){return (0.0 + trail.size())/nVars();}
+    //=============================================================
+
+
+
+
+
+};
+
+
+//=================================================================================================
+// Implementation of inline methods:
+
+inline CRef Solver::reason(Var x) const { return vardata[x].reason; }
+inline int  Solver::level (Var x) const { return vardata[x].level; }
+
+inline void Solver::insertVarOrder(Var x) {
+    //    Heap<VarOrderLt>& order_heap = VSIDS ? order_heap_VSIDS : order_heap_CHB;
+    Heap<VarOrderLt>& order_heap = DISTANCE ? order_heap_distance : ((!VSIDS)? order_heap_CHB:order_heap_VSIDS);
+    if (!order_heap.inHeap(x) && decision[x]) order_heap.insert(x); }
+
+inline void Solver::varDecayActivity() {
+    var_inc *= (1 / var_decay); }
+
+inline void Solver::varBumpActivity(Var v, double mult) {
+    if ( (activity_VSIDS[v] += var_inc * mult) > 1e100 ) {
+        // Rescale:
+        for (int i = 0; i < nVars(); i++)
+            activity_VSIDS[i] *= 1e-100;
+        var_inc *= 1e-100; }
+
+    // Update order_heap with respect to new activity:
+    if (order_heap_VSIDS.inHeap(v)) order_heap_VSIDS.decrease(v); }
+
+inline void Solver::claDecayActivity() { cla_inc *= (1 / clause_decay); }
+inline void Solver::claBumpActivity (Clause& c) {
+    if ( (c.activity() += cla_inc) > 1e20 ) {
+        // Rescale:
+        for (int i = 0; i < learnts_local.size(); i++)
+            ca[learnts_local[i]].activity() *= 1e-20;
+        cla_inc *= 1e-20; } }
+
+inline void Solver::checkGarbage(void){ return checkGarbage(garbage_frac); }
+inline void Solver::checkGarbage(double gf){
+    if (ca.wasted() > ca.size() * gf)
+        garbageCollect(); }
+
+// NOTE: enqueue does not set the ok flag! (only public methods do)
+inline bool     Solver::enqueue         (Lit p, CRef from)      { return value(p) != l_Undef ? value(p) != l_False : (uncheckedEnqueue(p, from), true); }
+inline bool     Solver::addClause       (const vec<Lit>& ps)    { ps.copyTo(add_tmp); return addClause_(add_tmp); }
+inline bool     Solver::addEmptyClause  ()                      { add_tmp.clear(); return addClause_(add_tmp); }
+inline bool     Solver::addClause       (Lit p)                 { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); }
+inline bool     Solver::addClause       (Lit p, Lit q)          { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); }
+inline bool     Solver::addClause       (Lit p, Lit q, Lit r)   { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); }
+inline bool     Solver::locked          (const Clause& c) const {
+    int i = c.size() != 2 ? 0 : (value(c[0]) == l_True ? 0 : 1);
+    return value(c[i]) == l_True && reason(var(c[i])) != CRef_Undef && ca.lea(reason(var(c[i]))) == &c;
+}
+inline void     Solver::newDecisionLevel()                      { trail_lim.push(trail.size()); }
+
+inline int      Solver::decisionLevel ()      const   { return trail_lim.size(); }
+inline uint32_t Solver::abstractLevel (Var x) const   { return 1 << (level(x) & 31); }
+inline lbool    Solver::value         (Var x) const   { return assigns[x]; }
+inline lbool    Solver::value         (Lit p) const   { return assigns[var(p)] ^ sign(p); }
+inline lbool    Solver::modelValue    (Var x) const   { return model[x]; }
+inline lbool    Solver::modelValue    (Lit p) const   { return model[var(p)] ^ sign(p); }
+inline int      Solver::nAssigns      ()      const   { return trail.size(); }
+inline int      Solver::nClauses      ()      const   { return clauses.size(); }
+inline int      Solver::nLearnts      ()      const   { return learnts_core.size() + learnts_tier2.size() + learnts_local.size(); }
+inline int      Solver::nVars         ()      const   { return vardata.size(); }
+inline int      Solver::nFreeVars     ()      const   { return (int)dec_vars - (trail_lim.size() == 0 ? trail.size() : trail_lim[0]); }
+inline void     Solver::setPolarity   (Var v, bool b) { polarity[v] = b; }
+inline void     Solver::setDecisionVar(Var v, bool b) 
+{ 
+    if      ( b && !decision[v]) dec_vars++;
+    else if (!b &&  decision[v]) dec_vars--;
+
+    decision[v] = b;
+    if (b && !order_heap_CHB.inHeap(v)){
+        order_heap_CHB.insert(v);
+        order_heap_VSIDS.insert(v);
+        order_heap_distance.insert(v);}
+}
+inline void     Solver::setConfBudget(int64_t x){ conflict_budget    = conflicts    + x; }
+inline void     Solver::setPropBudget(int64_t x){ propagation_budget = propagations + x; }
+inline void     Solver::interrupt(){ asynch_interrupt = true; }
+inline void     Solver::clearInterrupt(){ asynch_interrupt = false; }
+inline void     Solver::budgetOff(){ conflict_budget = propagation_budget = -1; }
+inline bool     Solver::withinBudget() const {
+    return !asynch_interrupt &&
+            (conflict_budget    < 0 || conflicts < (uint64_t)conflict_budget) &&
+            (propagation_budget < 0 || propagations < (uint64_t)propagation_budget); }
+
+// FIXME: after the introduction of asynchronous interrruptions the solve-versions that return a
+// pure bool do not give a safe interface. Either interrupts must be possible to turn off here, or
+// all calls to solve must return an 'lbool'. I'm not yet sure which I prefer.
+inline bool     Solver::solve         ()                    { budgetOff(); assumptions.clear(); return solve_() == l_True; }
+inline bool     Solver::solve         (Lit p)               { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_() == l_True; }
+inline bool     Solver::solve         (Lit p, Lit q)        { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_() == l_True; }
+inline bool     Solver::solve         (Lit p, Lit q, Lit r) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_() == l_True; }
+inline bool     Solver::solve         (const vec<Lit>& assumps){ budgetOff(); assumps.copyTo(assumptions); return solve_() == l_True; }
+inline lbool    Solver::solveLimited  (const vec<Lit>& assumps){ assumps.copyTo(assumptions); return solve_(); }
+inline bool     Solver::okay          ()      const   { return ok; }
+
+inline void     Solver::toDimacs     (const char* file){ vec<Lit> as; toDimacs(file, as); }
+inline void     Solver::toDimacs     (const char* file, Lit p){ vec<Lit> as; as.push(p); toDimacs(file, as); }
+inline void     Solver::toDimacs     (const char* file, Lit p, Lit q){ vec<Lit> as; as.push(p); as.push(q); toDimacs(file, as); }
+inline void     Solver::toDimacs     (const char* file, Lit p, Lit q, Lit r){ vec<Lit> as; as.push(p); as.push(q); as.push(r); toDimacs(file, as); }
+
+
+//=================================================================================================
+// Debug etc:
+
+
+//=================================================================================================
+}
+
+#endif

+ 447 - 0
sources/core/SolverTypes.h

@@ -0,0 +1,447 @@
+/***********************************************************************************[SolverTypes.h]
+MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+           Copyright (c) 2007-2010, Niklas Sorensson
+ 
+Chanseok Oh's MiniSat Patch Series -- Copyright (c) 2015, Chanseok Oh
+
+Maple_LCM, Based on MapleCOMSPS_DRUP -- Copyright (c) 2017, Mao Luo, Chu-Min LI, Fan Xiao: implementing a learnt clause minimisation approach
+Reference: M. Luo, C.-M. Li, F. Xiao, F. Manya, and Z. L. , “An effective learnt clause minimization approach for cdcl sat solvers,” in IJCAI-2017, 2017, pp. to–appear.
+ 
+Maple_LCM_Dist, Based on Maple_LCM -- Copyright (c) 2017, Fan Xiao, Chu-Min LI, Mao Luo: using a new branching heuristic called Distance at the beginning of search
+ 
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+
+#ifndef Minisat_SolverTypes_h
+#define Minisat_SolverTypes_h
+
+#include <assert.h>
+
+#include "mtl/IntTypes.h"
+#include "mtl/Alg.h"
+#include "mtl/Vec.h"
+#include "mtl/Map.h"
+#include "mtl/Alloc.h"
+
+namespace Minisat {
+
+//=================================================================================================
+// Variables, literals, lifted booleans, clauses:
+
+
+// NOTE! Variables are just integers. No abstraction here. They should be chosen from 0..N,
+// so that they can be used as array indices.
+
+typedef int Var;
+#define var_Undef (-1)
+
+
+struct Lit {
+    int     x;
+
+    // Use this as a constructor:
+    friend Lit mkLit(Var var, bool sign );
+
+    bool operator == (Lit p) const { return x == p.x; }
+    bool operator != (Lit p) const { return x != p.x; }
+    bool operator <  (Lit p) const { return x < p.x;  } // '<' makes p, ~p adjacent in the ordering.
+};
+
+
+inline  Lit  mkLit     (Var var, bool sign= false) { Lit p; p.x = var + var + (int)sign; return p; }
+inline  Lit  operator ~(Lit p)              { Lit q; q.x = p.x ^ 1; return q; }
+inline  Lit  operator ^(Lit p, bool b)      { Lit q; q.x = p.x ^ (unsigned int)b; return q; }
+inline  bool sign      (Lit p)              { return p.x & 1; }
+inline  int  var       (Lit p)              { return p.x >> 1; }
+
+// Mapping Literals to and from compact integers suitable for array indexing:
+inline  int  toInt     (Var v)              { return v; } 
+inline  int  toInt     (Lit p)              { return p.x; } 
+inline  Lit  toLit     (int i)              { Lit p; p.x = i; return p; } 
+
+//const Lit lit_Undef = mkLit(var_Undef, false);  // }- Useful special constants.
+//const Lit lit_Error = mkLit(var_Undef, true );  // }
+
+const Lit lit_Undef = { -2 };  // }- Useful special constants.
+const Lit lit_Error = { -1 };  // }
+
+//--------------------------------------
+inline int toFormal(Lit p) { return sign(p) ? -var(p) - 1 : var(p) + 1; }
+//=======================================
+
+//=================================================================================================
+// Lifted booleans:
+//
+// NOTE: this implementation is optimized for the case when comparisons between values are mostly
+//       between one variable and one constant. Some care had to be taken to make sure that gcc 
+//       does enough constant propagation to produce sensible code, and this appears to be somewhat
+//       fragile unfortunately.
+
+#define l_True  (lbool((uint8_t)0)) // gcc does not do constant propagation if these are real constants.
+#define l_False (lbool((uint8_t)1))
+#define l_Undef (lbool((uint8_t)2))
+
+class lbool {
+    uint8_t value;
+
+public:
+    explicit lbool(uint8_t v) : value(v) { }
+
+    lbool()       : value(0) { }
+    explicit lbool(bool x) : value(!x) { }
+
+    bool  operator == (lbool b) const { return ((b.value&2) & (value&2)) | (!(b.value&2)&(value == b.value)); }
+    bool  operator != (lbool b) const { return !(*this == b); }
+    lbool operator ^  (bool  b) const { return lbool((uint8_t)(value^(uint8_t)b)); }
+
+    lbool operator && (lbool b) const {
+        uint8_t sel = (this->value << 1) | (b.value << 3);
+        uint8_t v   = (0xF7F755F4 >> sel) & 3;
+        return lbool(v); }
+
+    lbool operator || (lbool b) const {
+        uint8_t sel = (this->value << 1) | (b.value << 3);
+        uint8_t v   = (0xFCFCF400 >> sel) & 3;
+        return lbool(v); }
+
+    friend int   toInt  (lbool l);
+    friend lbool toLbool(int   v);
+};
+inline int   toInt  (lbool l) { return l.value; }
+inline lbool toLbool(int   v) { return lbool((uint8_t)v);  }
+
+//=================================================================================================
+// Clause -- a simple class for representing a clause:
+
+class Clause;
+typedef RegionAllocator<uint32_t>::Ref CRef;
+
+class Clause {
+    struct {
+        unsigned mark      : 2;
+        unsigned learnt    : 1;
+        unsigned has_extra : 1;
+        unsigned reloced   : 1;
+        unsigned lbd       : 26;
+        unsigned removable : 1;
+        unsigned size      : 32;
+        //simplify
+        unsigned simplified : 1;}                            header;
+    union { Lit lit; float act; uint32_t abs; uint32_t touched; CRef rel; } data[0];
+
+    friend class ClauseAllocator;
+
+    // NOTE: This constructor cannot be used directly (doesn't allocate enough memory).
+    template<class V>
+    Clause(const V& ps, bool use_extra, bool learnt) {
+        header.mark      = 0;
+        header.learnt    = learnt;
+        header.has_extra = learnt | use_extra;
+        header.reloced   = 0;
+        header.size      = ps.size();
+        header.lbd       = 0;
+        header.removable = 1;
+        //simplify
+        //
+        header.simplified = 0;
+
+        for (int i = 0; i < ps.size(); i++)
+            data[i].lit = ps[i];
+
+        if (header.has_extra){
+            if (header.learnt){
+                data[header.size].act = 0;
+                data[header.size+1].touched = 0;
+            }else
+                calcAbstraction(); }
+    }
+
+public:
+    void calcAbstraction() {
+        assert(header.has_extra);
+        uint32_t abstraction = 0;
+        for (int i = 0; i < size(); i++)
+            abstraction |= 1 << (var(data[i].lit) & 31);
+        data[header.size].abs = abstraction;  }
+
+
+    int          size        ()      const   { return header.size; }
+    void         shrink      (int i)         { assert(i <= size()); if (header.has_extra) data[header.size-i] = data[header.size]; header.size -= i; }
+    void         pop         ()              { shrink(1); }
+    bool         learnt      ()      const   { return header.learnt; }
+    bool         has_extra   ()      const   { return header.has_extra; }
+    uint32_t     mark        ()      const   { return header.mark; }
+    void         mark        (uint32_t m)    { header.mark = m; }
+    const Lit&   last        ()      const   { return data[header.size-1].lit; }
+
+    bool         reloced     ()      const   { return header.reloced; }
+    CRef         relocation  ()      const   { return data[0].rel; }
+    void         relocate    (CRef c)        { header.reloced = 1; data[0].rel = c; }
+
+    int          lbd         ()      const   { return header.lbd; }
+    void         set_lbd     (int lbd)       { header.lbd = lbd; }
+    bool         removable   ()      const   { return header.removable; }
+    void         removable   (bool b)        { header.removable = b; }
+
+    // NOTE: somewhat unsafe to change the clause in-place! Must manually call 'calcAbstraction' afterwards for
+    //       subsumption operations to behave correctly.
+    Lit&         operator [] (int i)         { return data[i].lit; }
+    Lit          operator [] (int i) const   { return data[i].lit; }
+    operator const Lit* (void) const         { return (Lit*)data; }
+
+    uint32_t&    touched     ()              { assert(header.has_extra && header.learnt); return data[header.size+1].touched; }
+    float&       activity    ()              { assert(header.has_extra); return data[header.size].act; }
+    uint32_t     abstraction () const        { assert(header.has_extra); return data[header.size].abs; }
+
+    Lit          subsumes    (const Clause& other) const;
+    void         strengthen  (Lit p);
+    // simplify
+    //
+    void setSimplified(bool b) { header.simplified = b; }
+    bool simplified() { return header.simplified; }
+};
+
+
+//=================================================================================================
+// ClauseAllocator -- a simple class for allocating memory for clauses:
+
+
+const CRef CRef_Undef = RegionAllocator<uint32_t>::Ref_Undef;
+class ClauseAllocator : public RegionAllocator<uint32_t>
+{
+    static int clauseWord32Size(int size, int extras){
+        return (sizeof(Clause) + (sizeof(Lit) * (size + extras))) / sizeof(uint32_t); }
+public:
+    bool extra_clause_field;
+
+    ClauseAllocator(uint32_t start_cap) : RegionAllocator<uint32_t>(start_cap), extra_clause_field(false){}
+    ClauseAllocator() : extra_clause_field(false){}
+
+    void moveTo(ClauseAllocator& to){
+        to.extra_clause_field = extra_clause_field;
+        RegionAllocator<uint32_t>::moveTo(to); }
+
+    template<class Lits>
+    CRef alloc(const Lits& ps, bool learnt = false)
+    {
+        assert(sizeof(Lit)      == sizeof(uint32_t));
+        assert(sizeof(float)    == sizeof(uint32_t));
+        int extras = learnt ? 2 : (int)extra_clause_field;
+
+        CRef cid = RegionAllocator<uint32_t>::alloc(clauseWord32Size(ps.size(), extras));
+        new (lea(cid)) Clause(ps, extra_clause_field, learnt);
+
+        return cid;
+    }
+
+    // Deref, Load Effective Address (LEA), Inverse of LEA (AEL):
+    Clause&       operator[](Ref r)       { return (Clause&)RegionAllocator<uint32_t>::operator[](r); }
+    const Clause& operator[](Ref r) const { return (Clause&)RegionAllocator<uint32_t>::operator[](r); }
+    Clause*       lea       (Ref r)       { return (Clause*)RegionAllocator<uint32_t>::lea(r); }
+    const Clause* lea       (Ref r) const { return (Clause*)RegionAllocator<uint32_t>::lea(r); }
+    Ref           ael       (const Clause* t){ return RegionAllocator<uint32_t>::ael((uint32_t*)t); }
+
+    void free(CRef cid)
+    {
+        Clause& c = operator[](cid);
+        int extras = c.learnt() ? 2 : (int)c.has_extra();
+        RegionAllocator<uint32_t>::free(clauseWord32Size(c.size(), extras));
+    }
+
+    void reloc(CRef& cr, ClauseAllocator& to)
+    {
+        Clause& c = operator[](cr);
+        
+        if (c.reloced()) { cr = c.relocation(); return; }
+        
+        cr = to.alloc(c, c.learnt());
+        c.relocate(cr);
+        
+        // Copy extra data-fields:
+        // (This could be cleaned-up. Generalize Clause-constructor to be applicable here instead?)
+        to[cr].mark(c.mark());
+        if (to[cr].learnt()){
+            to[cr].touched() = c.touched();
+            to[cr].activity() = c.activity();
+            to[cr].set_lbd(c.lbd());
+            to[cr].removable(c.removable());
+            // simplify
+            //
+            to[cr].setSimplified(c.simplified());
+        }
+        else if (to[cr].has_extra()) to[cr].calcAbstraction();
+    }
+};
+
+
+//=================================================================================================
+// OccLists -- a class for maintaining occurence lists with lazy deletion:
+
+template<class Idx, class Vec, class Deleted>
+class OccLists
+{
+    vec<Vec>  occs;
+    vec<char> dirty;
+    vec<Idx>  dirties;
+    Deleted   deleted;
+
+public:
+    OccLists(const Deleted& d) : deleted(d) {}
+    
+    void  init      (const Idx& idx){ occs.growTo(toInt(idx)+1); dirty.growTo(toInt(idx)+1, 0); }
+    // Vec&  operator[](const Idx& idx){ return occs[toInt(idx)]; }
+    Vec&  operator[](const Idx& idx){ return occs[toInt(idx)]; }
+    Vec&  lookup    (const Idx& idx){ if (dirty[toInt(idx)]) clean(idx); return occs[toInt(idx)]; }
+
+    void  cleanAll  ();
+    void  clean     (const Idx& idx);
+    void  smudge    (const Idx& idx){
+        if (dirty[toInt(idx)] == 0){
+            dirty[toInt(idx)] = 1;
+            dirties.push(idx);
+        }
+    }
+
+    void  clear(bool free = true){
+        occs   .clear(free);
+        dirty  .clear(free);
+        dirties.clear(free);
+    }
+};
+
+
+template<class Idx, class Vec, class Deleted>
+void OccLists<Idx,Vec,Deleted>::cleanAll()
+{
+    for (int i = 0; i < dirties.size(); i++)
+        // Dirties may contain duplicates so check here if a variable is already cleaned:
+        if (dirty[toInt(dirties[i])])
+            clean(dirties[i]);
+    dirties.clear();
+}
+
+
+template<class Idx, class Vec, class Deleted>
+void OccLists<Idx,Vec,Deleted>::clean(const Idx& idx)
+{
+    Vec& vec = occs[toInt(idx)];
+    int  i, j;
+    for (i = j = 0; i < vec.size(); i++)
+        if (!deleted(vec[i]))
+            vec[j++] = vec[i];
+    vec.shrink(i - j);
+    dirty[toInt(idx)] = 0;
+}
+
+
+//=================================================================================================
+// CMap -- a class for mapping clauses to values:
+
+
+template<class T>
+class CMap
+{
+    struct CRefHash {
+        uint32_t operator()(CRef cr) const { return (uint32_t)cr; } };
+
+    typedef Map<CRef, T, CRefHash> HashTable;
+    HashTable map;
+
+public:
+    // Size-operations:
+    void     clear       ()                           { map.clear(); }
+    int      size        ()                const      { return map.elems(); }
+
+    
+    // Insert/Remove/Test mapping:
+    void     insert      (CRef cr, const T& t){ map.insert(cr, t); }
+    void     growTo      (CRef cr, const T& t){ map.insert(cr, t); } // NOTE: for compatibility
+    void     remove      (CRef cr)            { map.remove(cr); }
+    bool     has         (CRef cr, T& t)      { return map.peek(cr, t); }
+
+    // Vector interface (the clause 'c' must already exist):
+    const T& operator [] (CRef cr) const      { return map[cr]; }
+    T&       operator [] (CRef cr)            { return map[cr]; }
+
+    // Iteration (not transparent at all at the moment):
+    int  bucket_count() const { return map.bucket_count(); }
+    const vec<typename HashTable::Pair>& bucket(int i) const { return map.bucket(i); }
+
+    // Move contents to other map:
+    void moveTo(CMap& other){ map.moveTo(other.map); }
+
+    // TMP debug:
+    void debug(){
+        printf("c --- size = %d, bucket_count = %d\n", size(), map.bucket_count()); }
+};
+
+
+/*_________________________________________________________________________________________________
+|
+|  subsumes : (other : const Clause&)  ->  Lit
+|  
+|  Description:
+|       Checks if clause subsumes 'other', and at the same time, if it can be used to simplify 'other'
+|       by subsumption resolution.
+|  
+|    Result:
+|       lit_Error  - No subsumption or simplification
+|       lit_Undef  - Clause subsumes 'other'
+|       p          - The literal p can be deleted from 'other'
+|________________________________________________________________________________________________@*/
+inline Lit Clause::subsumes(const Clause& other) const
+{
+    //if (other.size() < size() || (extra.abst & ~other.extra.abst) != 0)
+    //if (other.size() < size() || (!learnt() && !other.learnt() && (extra.abst & ~other.extra.abst) != 0))
+    assert(!header.learnt);   assert(!other.header.learnt);
+    assert(header.has_extra); assert(other.header.has_extra);
+    if (other.header.size < header.size || (data[header.size].abs & ~other.data[other.header.size].abs) != 0)
+        return lit_Error;
+
+    Lit        ret = lit_Undef;
+    const Lit* c   = (const Lit*)(*this);
+    const Lit* d   = (const Lit*)other;
+
+    for (unsigned i = 0; i < header.size; i++) {
+        // search for c[i] or ~c[i]
+        for (unsigned j = 0; j < other.header.size; j++)
+            if (c[i] == d[j])
+                goto ok;
+            else if (ret == lit_Undef && c[i] == ~d[j]){
+                ret = c[i];
+                goto ok;
+            }
+
+        // did not find it
+        return lit_Error;
+ok:;
+    }
+
+    return ret;
+}
+
+inline void Clause::strengthen(Lit p)
+{
+    remove(*this, p);
+    calcAbstraction();
+}
+
+//=================================================================================================
+}
+
+#endif

+ 84 - 0
sources/mtl/Alg.h

@@ -0,0 +1,84 @@
+/*******************************************************************************************[Alg.h]
+Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2007-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_Alg_h
+#define Minisat_Alg_h
+
+#include "mtl/Vec.h"
+
+namespace Minisat {
+
+//=================================================================================================
+// Useful functions on vector-like types:
+
+//=================================================================================================
+// Removing and searching for elements:
+//
+
+template<class V, class T>
+static inline void remove(V& ts, const T& t)
+{
+    int j = 0;
+    for (; j < ts.size() && ts[j] != t; j++);
+    assert(j < ts.size());
+    for (; j < ts.size()-1; j++) ts[j] = ts[j+1];
+    ts.pop();
+}
+
+
+template<class V, class T>
+static inline bool find(V& ts, const T& t)
+{
+    int j = 0;
+    for (; j < ts.size() && ts[j] != t; j++);
+    return j < ts.size();
+}
+
+
+//=================================================================================================
+// Copying vectors with support for nested vector types:
+//
+
+// Base case:
+template<class T>
+static inline void copy(const T& from, T& to)
+{
+    to = from;
+}
+
+// Recursive case:
+template<class T>
+static inline void copy(const vec<T>& from, vec<T>& to, bool append = false)
+{
+    if (!append)
+        to.clear();
+    for (int i = 0; i < from.size(); i++){
+        to.push();
+        copy(from[i], to.last());
+    }
+}
+
+template<class T>
+static inline void append(const vec<T>& from, vec<T>& to){ copy(from, to, true); }
+
+//=================================================================================================
+}
+
+#endif

+ 131 - 0
sources/mtl/Alloc.h

@@ -0,0 +1,131 @@
+/*****************************************************************************************[Alloc.h]
+Copyright (c) 2008-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+
+#ifndef Minisat_Alloc_h
+#define Minisat_Alloc_h
+
+#include "mtl/XAlloc.h"
+#include "mtl/Vec.h"
+
+namespace Minisat {
+
+//=================================================================================================
+// Simple Region-based memory allocator:
+
+template<class T>
+class RegionAllocator
+{
+    T*        memory;
+    uint32_t  sz;
+    uint32_t  cap;
+    uint32_t  wasted_;
+
+    void capacity(uint32_t min_cap);
+
+ public:
+    // TODO: make this a class for better type-checking?
+    typedef uint32_t Ref;
+    enum { Ref_Undef = UINT32_MAX };
+    enum { Unit_Size = sizeof(uint32_t) };
+
+    explicit RegionAllocator(uint32_t start_cap = 1024*1024) : memory(NULL), sz(0), cap(0), wasted_(0){ capacity(start_cap); }
+    ~RegionAllocator()
+    {
+        if (memory != NULL)
+            ::free(memory);
+    }
+
+
+    uint32_t size      () const      { return sz; }
+    uint32_t wasted    () const      { return wasted_; }
+
+    Ref      alloc     (int size); 
+    void     free      (int size)    { wasted_ += size; }
+
+    // Deref, Load Effective Address (LEA), Inverse of LEA (AEL):
+    T&       operator[](Ref r)       { assert(r >= 0 && r < sz); return memory[r]; }
+    const T& operator[](Ref r) const { assert(r >= 0 && r < sz); return memory[r]; }
+
+    T*       lea       (Ref r)       { assert(r >= 0 && r < sz); return &memory[r]; }
+    const T* lea       (Ref r) const { assert(r >= 0 && r < sz); return &memory[r]; }
+    Ref      ael       (const T* t)  { assert((void*)t >= (void*)&memory[0] && (void*)t < (void*)&memory[sz-1]);
+        return  (Ref)(t - &memory[0]); }
+
+    void     moveTo(RegionAllocator& to) {
+        if (to.memory != NULL) ::free(to.memory);
+        to.memory = memory;
+        to.sz = sz;
+        to.cap = cap;
+        to.wasted_ = wasted_;
+
+        memory = NULL;
+        sz = cap = wasted_ = 0;
+    }
+
+
+};
+
+template<class T>
+void RegionAllocator<T>::capacity(uint32_t min_cap)
+{
+    if (cap >= min_cap) return;
+
+    uint32_t prev_cap = cap;
+    while (cap < min_cap){
+        // NOTE: Multiply by a factor (13/8) without causing overflow, then add 2 and make the
+        // result even by clearing the least significant bit. The resulting sequence of capacities
+        // is carefully chosen to hit a maximum capacity that is close to the '2^32-1' limit when
+        // using 'uint32_t' as indices so that as much as possible of this space can be used.
+        uint32_t delta = ((cap >> 1) + (cap >> 3) + 2) & ~1;
+        cap += delta;
+
+        if (cap <= prev_cap)
+            throw OutOfMemoryException();
+    }
+    // printf(" .. (%p) cap = %u\n", this, cap);
+
+    assert(cap > 0);
+    memory = (T*)xrealloc(memory, sizeof(T)*cap);
+}
+
+
+template<class T>
+typename RegionAllocator<T>::Ref
+RegionAllocator<T>::alloc(int size)
+{ 
+    // printf("ALLOC called (this = %p, size = %d)\n", this, size); fflush(stdout);
+    assert(size > 0);
+    capacity(sz + size);
+
+    uint32_t prev_sz = sz;
+    sz += size;
+    
+    // Handle overflow:
+    if (sz < prev_sz)
+        throw OutOfMemoryException();
+
+    return prev_sz;
+}
+
+
+//=================================================================================================
+}
+
+#endif

+ 148 - 0
sources/mtl/Heap.h

@@ -0,0 +1,148 @@
+/******************************************************************************************[Heap.h]
+Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2007-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_Heap_h
+#define Minisat_Heap_h
+
+#include "mtl/Vec.h"
+
+namespace Minisat {
+
+//=================================================================================================
+// A heap implementation with support for decrease/increase key.
+
+
+template<class Comp>
+class Heap {
+    Comp     lt;       // The heap is a minimum-heap with respect to this comparator
+    vec<int> heap;     // Heap of integers
+    vec<int> indices;  // Each integers position (index) in the Heap
+
+    // Index "traversal" functions
+    static inline int left  (int i) { return i*2+1; }
+    static inline int right (int i) { return (i+1)*2; }
+    static inline int parent(int i) { return (i-1) >> 1; }
+
+
+    void percolateUp(int i)
+    {
+        int x  = heap[i];
+        int p  = parent(i);
+        
+        while (i != 0 && lt(x, heap[p])){
+            heap[i]          = heap[p];
+            indices[heap[p]] = i;
+            i                = p;
+            p                = parent(p);
+        }
+        heap   [i] = x;
+        indices[x] = i;
+    }
+
+
+    void percolateDown(int i)
+    {
+        int x = heap[i];
+        while (left(i) < heap.size()){
+            int child = right(i) < heap.size() && lt(heap[right(i)], heap[left(i)]) ? right(i) : left(i);
+            if (!lt(heap[child], x)) break;
+            heap[i]          = heap[child];
+            indices[heap[i]] = i;
+            i                = child;
+        }
+        heap   [i] = x;
+        indices[x] = i;
+    }
+
+
+  public:
+    Heap(const Comp& c) : lt(c) { }
+
+    int  size      ()          const { return heap.size(); }
+    bool empty     ()          const { return heap.size() == 0; }
+    bool inHeap    (int n)     const { return n < indices.size() && indices[n] >= 0; }
+    int  operator[](int index) const { assert(index < heap.size()); return heap[index]; }
+
+
+    void decrease  (int n) { assert(inHeap(n)); percolateUp  (indices[n]); }
+    void increase  (int n) { assert(inHeap(n)); percolateDown(indices[n]); }
+
+
+    // Safe variant of insert/decrease/increase:
+    void update(int n)
+    {
+        if (!inHeap(n))
+            insert(n);
+        else {
+            percolateUp(indices[n]);
+            percolateDown(indices[n]); }
+    }
+
+
+    void insert(int n)
+    {
+        indices.growTo(n+1, -1);
+        assert(!inHeap(n));
+
+        indices[n] = heap.size();
+        heap.push(n);
+        percolateUp(indices[n]); 
+    }
+
+
+    int  removeMin()
+    {
+        int x            = heap[0];
+        heap[0]          = heap.last();
+        indices[heap[0]] = 0;
+        indices[x]       = -1;
+        heap.pop();
+        if (heap.size() > 1) percolateDown(0);
+        return x; 
+    }
+
+
+    // Rebuild the heap from scratch, using the elements in 'ns':
+    void build(const vec<int>& ns) {
+        for (int i = 0; i < heap.size(); i++)
+            indices[heap[i]] = -1;
+        heap.clear();
+
+        for (int i = 0; i < ns.size(); i++){
+            indices[ns[i]] = i;
+            heap.push(ns[i]); }
+
+        for (int i = heap.size() / 2 - 1; i >= 0; i--)
+            percolateDown(i);
+    }
+
+    void clear(bool dealloc = false) 
+    { 
+        for (int i = 0; i < heap.size(); i++)
+            indices[heap[i]] = -1;
+        heap.clear(dealloc); 
+    }
+};
+
+
+//=================================================================================================
+}
+
+#endif

+ 42 - 0
sources/mtl/IntTypes.h

@@ -0,0 +1,42 @@
+/**************************************************************************************[IntTypes.h]
+Copyright (c) 2009-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_IntTypes_h
+#define Minisat_IntTypes_h
+
+#ifdef __sun
+    // Not sure if there are newer versions that support C99 headers. The
+    // needed features are implemented in the headers below though:
+
+#   include <sys/int_types.h>
+#   include <sys/int_fmtio.h>
+#   include <sys/int_limits.h>
+
+#else
+
+#   include <stdint.h>
+#   include <inttypes.h>
+
+#endif
+
+#include <limits.h>
+
+//=================================================================================================
+
+#endif

+ 193 - 0
sources/mtl/Map.h

@@ -0,0 +1,193 @@
+/*******************************************************************************************[Map.h]
+Copyright (c) 2006-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_Map_h
+#define Minisat_Map_h
+
+#include "mtl/IntTypes.h"
+#include "mtl/Vec.h"
+
+namespace Minisat {
+
+//=================================================================================================
+// Default hash/equals functions
+//
+
+template<class K> struct Hash  { uint32_t operator()(const K& k)               const { return hash(k);  } };
+template<class K> struct Equal { bool     operator()(const K& k1, const K& k2) const { return k1 == k2; } };
+
+template<class K> struct DeepHash  { uint32_t operator()(const K* k)               const { return hash(*k);  } };
+template<class K> struct DeepEqual { bool     operator()(const K* k1, const K* k2) const { return *k1 == *k2; } };
+
+static inline uint32_t hash(uint32_t x){ return x; }
+static inline uint32_t hash(uint64_t x){ return (uint32_t)x; }
+static inline uint32_t hash(int32_t x) { return (uint32_t)x; }
+static inline uint32_t hash(int64_t x) { return (uint32_t)x; }
+
+
+//=================================================================================================
+// Some primes
+//
+
+static const int nprimes          = 25;
+static const int primes [nprimes] = { 31, 73, 151, 313, 643, 1291, 2593, 5233, 10501, 21013, 42073, 84181, 168451, 337219, 674701, 1349473, 2699299, 5398891, 10798093, 21596719, 43193641, 86387383, 172775299, 345550609, 691101253 };
+
+//=================================================================================================
+// Hash table implementation of Maps
+//
+
+template<class K, class D, class H = Hash<K>, class E = Equal<K> >
+class Map {
+ public:
+    struct Pair { K key; D data; };
+
+ private:
+    H          hash;
+    E          equals;
+
+    vec<Pair>* table;
+    int        cap;
+    int        size;
+
+    // Don't allow copying (error prone):
+    Map<K,D,H,E>&  operator = (Map<K,D,H,E>& other) { assert(0); }
+                   Map        (Map<K,D,H,E>& other) { assert(0); }
+
+    bool    checkCap(int new_size) const { return new_size > cap; }
+
+    int32_t index  (const K& k) const { return hash(k) % cap; }
+    void   _insert (const K& k, const D& d) { 
+        vec<Pair>& ps = table[index(k)];
+        ps.push(); ps.last().key = k; ps.last().data = d; }
+
+    void    rehash () {
+        const vec<Pair>* old = table;
+
+        int old_cap = cap;
+        int newsize = primes[0];
+        for (int i = 1; newsize <= cap && i < nprimes; i++)
+           newsize = primes[i];
+
+        table = new vec<Pair>[newsize];
+        cap   = newsize;
+
+        for (int i = 0; i < old_cap; i++){
+            for (int j = 0; j < old[i].size(); j++){
+                _insert(old[i][j].key, old[i][j].data); }}
+
+        delete [] old;
+
+        // printf(" --- rehashing, old-cap=%d, new-cap=%d\n", cap, newsize);
+    }
+
+    
+ public:
+
+    Map () : table(NULL), cap(0), size(0) {}
+    Map (const H& h, const E& e) : hash(h), equals(e), table(NULL), cap(0), size(0){}
+    ~Map () { delete [] table; }
+
+    // PRECONDITION: the key must already exist in the map.
+    const D& operator [] (const K& k) const
+    {
+        assert(size != 0);
+        const D*         res = NULL;
+        const vec<Pair>& ps  = table[index(k)];
+        for (int i = 0; i < ps.size(); i++)
+            if (equals(ps[i].key, k))
+                res = &ps[i].data;
+        assert(res != NULL);
+        return *res;
+    }
+
+    // PRECONDITION: the key must already exist in the map.
+    D& operator [] (const K& k)
+    {
+        assert(size != 0);
+        D*         res = NULL;
+        vec<Pair>& ps  = table[index(k)];
+        for (int i = 0; i < ps.size(); i++)
+            if (equals(ps[i].key, k))
+                res = &ps[i].data;
+        assert(res != NULL);
+        return *res;
+    }
+
+    // PRECONDITION: the key must *NOT* exist in the map.
+    void insert (const K& k, const D& d) { if (checkCap(size+1)) rehash(); _insert(k, d); size++; }
+    bool peek   (const K& k, D& d) const {
+        if (size == 0) return false;
+        const vec<Pair>& ps = table[index(k)];
+        for (int i = 0; i < ps.size(); i++)
+            if (equals(ps[i].key, k)){
+                d = ps[i].data;
+                return true; } 
+        return false;
+    }
+
+    bool has   (const K& k) const {
+        if (size == 0) return false;
+        const vec<Pair>& ps = table[index(k)];
+        for (int i = 0; i < ps.size(); i++)
+            if (equals(ps[i].key, k))
+                return true;
+        return false;
+    }
+
+    // PRECONDITION: the key must exist in the map.
+    void remove(const K& k) {
+        assert(table != NULL);
+        vec<Pair>& ps = table[index(k)];
+        int j = 0;
+        for (; j < ps.size() && !equals(ps[j].key, k); j++);
+        assert(j < ps.size());
+        ps[j] = ps.last();
+        ps.pop();
+        size--;
+    }
+
+    void clear  () {
+        cap = size = 0;
+        delete [] table;
+        table = NULL;
+    }
+
+    int  elems() const { return size; }
+    int  bucket_count() const { return cap; }
+
+    // NOTE: the hash and equality objects are not moved by this method:
+    void moveTo(Map& other){
+        delete [] other.table;
+
+        other.table = table;
+        other.cap   = cap;
+        other.size  = size;
+
+        table = NULL;
+        size = cap = 0;
+    }
+
+    // NOTE: given a bit more time, I could make a more C++-style iterator out of this:
+    const vec<Pair>& bucket(int i) const { return table[i]; }
+};
+
+//=================================================================================================
+}
+
+#endif

+ 69 - 0
sources/mtl/Queue.h

@@ -0,0 +1,69 @@
+/*****************************************************************************************[Queue.h]
+Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2007-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_Queue_h
+#define Minisat_Queue_h
+
+#include "mtl/Vec.h"
+
+namespace Minisat {
+
+//=================================================================================================
+
+template<class T>
+class Queue {
+    vec<T>  buf;
+    int     first;
+    int     end;
+
+public:
+    typedef T Key;
+
+    Queue() : buf(1), first(0), end(0) {}
+
+    void clear (bool dealloc = false) { buf.clear(dealloc); buf.growTo(1); first = end = 0; }
+    int  size  () const { return (end >= first) ? end - first : end - first + buf.size(); }
+
+    const T& operator [] (int index) const  { assert(index >= 0); assert(index < size()); return buf[(first + index) % buf.size()]; }
+    T&       operator [] (int index)        { assert(index >= 0); assert(index < size()); return buf[(first + index) % buf.size()]; }
+
+    T    peek  () const { assert(first != end); return buf[first]; }
+    void pop   () { assert(first != end); first++; if (first == buf.size()) first = 0; }
+    void insert(T elem) {   // INVARIANT: buf[end] is always unused
+        buf[end++] = elem;
+        if (end == buf.size()) end = 0;
+        if (first == end){  // Resize:
+            vec<T>  tmp((buf.size()*3 + 1) >> 1);
+            //**/printf("queue alloc: %d elems (%.1f MB)\n", tmp.size(), tmp.size() * sizeof(T) / 1000000.0);
+            int     i = 0;
+            for (int j = first; j < buf.size(); j++) tmp[i++] = buf[j];
+            for (int j = 0    ; j < end       ; j++) tmp[i++] = buf[j];
+            first = 0;
+            end   = buf.size();
+            tmp.moveTo(buf);
+        }
+    }
+};
+
+
+//=================================================================================================
+}
+
+#endif

+ 98 - 0
sources/mtl/Sort.h

@@ -0,0 +1,98 @@
+/******************************************************************************************[Sort.h]
+Copyright (c) 2003-2007, Niklas Een, Niklas Sorensson
+Copyright (c) 2007-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_Sort_h
+#define Minisat_Sort_h
+
+#include "mtl/Vec.h"
+
+//=================================================================================================
+// Some sorting algorithms for vec's
+
+
+namespace Minisat {
+
+template<class T>
+struct LessThan_default {
+    bool operator () (T x, T y) { return x < y; }
+};
+
+
+template <class T, class LessThan>
+void selectionSort(T* array, int size, LessThan lt)
+{
+    int     i, j, best_i;
+    T       tmp;
+
+    for (i = 0; i < size-1; i++){
+        best_i = i;
+        for (j = i+1; j < size; j++){
+            if (lt(array[j], array[best_i]))
+                best_i = j;
+        }
+        tmp = array[i]; array[i] = array[best_i]; array[best_i] = tmp;
+    }
+}
+template <class T> static inline void selectionSort(T* array, int size) {
+    selectionSort(array, size, LessThan_default<T>()); }
+
+template <class T, class LessThan>
+void sort(T* array, int size, LessThan lt)
+{
+    if (size <= 15)
+        selectionSort(array, size, lt);
+
+    else{
+        T           pivot = array[size / 2];
+        T           tmp;
+        int         i = -1;
+        int         j = size;
+
+        for(;;){
+            do i++; while(lt(array[i], pivot));
+            do j--; while(lt(pivot, array[j]));
+
+            if (i >= j) break;
+
+            tmp = array[i]; array[i] = array[j]; array[j] = tmp;
+        }
+
+        sort(array    , i     , lt);
+        sort(&array[i], size-i, lt);
+    }
+}
+template <class T> static inline void sort(T* array, int size) {
+    sort(array, size, LessThan_default<T>()); }
+
+
+//=================================================================================================
+// For 'vec's:
+
+
+template <class T, class LessThan> void sort(vec<T>& v, LessThan lt) {
+    sort((T*)v, v.size(), lt); }
+template <class T> void sort(vec<T>& v) {
+    sort(v, LessThan_default<T>()); }
+
+
+//=================================================================================================
+}
+
+#endif

+ 130 - 0
sources/mtl/Vec.h

@@ -0,0 +1,130 @@
+/*******************************************************************************************[Vec.h]
+Copyright (c) 2003-2007, Niklas Een, Niklas Sorensson
+Copyright (c) 2007-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_Vec_h
+#define Minisat_Vec_h
+
+#include <assert.h>
+#include <new>
+
+#include "mtl/IntTypes.h"
+#include "mtl/XAlloc.h"
+
+namespace Minisat {
+
+//=================================================================================================
+// Automatically resizable arrays
+//
+// NOTE! Don't use this vector on datatypes that cannot be re-located in memory (with realloc)
+
+template<class T>
+class vec {
+    T*  data;
+    int sz;
+    int cap;
+
+    // Don't allow copying (error prone):
+    vec<T>&  operator = (vec<T>& other) { assert(0); return *this; }
+             vec        (vec<T>& other) { assert(0); }
+             
+    // Helpers for calculating next capacity:
+    static inline int  imax   (int x, int y) { int mask = (y-x) >> (sizeof(int)*8-1); return (x&mask) + (y&(~mask)); }
+    //static inline void nextCap(int& cap){ cap += ((cap >> 1) + 2) & ~1; }
+    static inline void nextCap(int& cap){ cap += ((cap >> 1) + 2) & ~1; }
+
+public:
+    // Constructors:
+    vec()                       : data(NULL) , sz(0)   , cap(0)    { }
+    explicit vec(int size)      : data(NULL) , sz(0)   , cap(0)    { growTo(size); }
+    vec(int size, const T& pad) : data(NULL) , sz(0)   , cap(0)    { growTo(size, pad); }
+   ~vec()                                                          { clear(true); }
+
+    // Pointer to first element:
+    operator T*       (void)           { return data; }
+
+    // Size operations:
+    int      size     (void) const     { return sz; }
+    void     shrink   (int nelems)     { assert(nelems <= sz); for (int i = 0; i < nelems; i++) sz--, data[sz].~T(); }
+    void     shrink_  (int nelems)     { assert(nelems <= sz); sz -= nelems; }
+    int      capacity (void) const     { return cap; }
+    void     capacity (int min_cap);
+    void     growTo   (int size);
+    void     growTo   (int size, const T& pad);
+    void     clear    (bool dealloc = false);
+
+    // Stack interface:
+    void     push  (void)              { if (sz == cap) capacity(sz+1); new (&data[sz]) T(); sz++; }
+    void     push  (const T& elem)     { if (sz == cap) capacity(sz+1); data[sz++] = elem; }
+    void     push_ (const T& elem)     { assert(sz < cap); data[sz++] = elem; }
+    void     pop   (void)              { assert(sz > 0); sz--, data[sz].~T(); }
+    // NOTE: it seems possible that overflow can happen in the 'sz+1' expression of 'push()', but
+    // in fact it can not since it requires that 'cap' is equal to INT_MAX. This in turn can not
+    // happen given the way capacities are calculated (below). Essentially, all capacities are
+    // even, but INT_MAX is odd.
+
+    const T& last  (void) const        { return data[sz-1]; }
+    T&       last  (void)              { return data[sz-1]; }
+
+    // Vector interface:
+    const T& operator [] (int index) const { return data[index]; }
+    T&       operator [] (int index)       { return data[index]; }
+
+    // Duplicatation (preferred instead):
+    void copyTo(vec<T>& copy) const { copy.clear(); copy.growTo(sz); for (int i = 0; i < sz; i++) copy[i] = data[i]; }
+    void moveTo(vec<T>& dest) { dest.clear(true); dest.data = data; dest.sz = sz; dest.cap = cap; data = NULL; sz = 0; cap = 0; }
+};
+
+
+template<class T>
+void vec<T>::capacity(int min_cap) {
+    if (cap >= min_cap) return;
+    int add = imax((min_cap - cap + 1) & ~1, ((cap >> 1) + 2) & ~1);   // NOTE: grow by approximately 3/2
+    if (add > INT_MAX - cap || ((data = (T*)::realloc(data, (cap += add) * sizeof(T))) == NULL) && errno == ENOMEM)
+        throw OutOfMemoryException();
+ }
+
+
+template<class T>
+void vec<T>::growTo(int size, const T& pad) {
+    if (sz >= size) return;
+    capacity(size);
+    for (int i = sz; i < size; i++) data[i] = pad;
+    sz = size; }
+
+
+template<class T>
+void vec<T>::growTo(int size) {
+    if (sz >= size) return;
+    capacity(size);
+    for (int i = sz; i < size; i++) new (&data[i]) T();
+    sz = size; }
+
+
+template<class T>
+void vec<T>::clear(bool dealloc) {
+    if (data != NULL){
+        for (int i = 0; i < sz; i++) data[i].~T();
+        sz = 0;
+        if (dealloc) free(data), data = NULL, cap = 0; } }
+
+//=================================================================================================
+}
+
+#endif

+ 45 - 0
sources/mtl/XAlloc.h

@@ -0,0 +1,45 @@
+/****************************************************************************************[XAlloc.h]
+Copyright (c) 2009-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+
+#ifndef Minisat_XAlloc_h
+#define Minisat_XAlloc_h
+
+#include <errno.h>
+#include <stdlib.h>
+
+namespace Minisat {
+
+//=================================================================================================
+// Simple layer on top of malloc/realloc to catch out-of-memory situtaions and provide some typing:
+
+class OutOfMemoryException{};
+static inline void* xrealloc(void *ptr, size_t size)
+{
+    void* mem = realloc(ptr, size);
+    if (mem == NULL && errno == ENOMEM){
+        throw OutOfMemoryException();
+    }else
+        return mem;
+}
+
+//=================================================================================================
+}
+
+#endif

+ 6 - 0
sources/mtl/config.mk

@@ -0,0 +1,6 @@
+##
+##  This file is for system specific configurations. For instance, on
+##  some systems the path to zlib needs to be added. Example:
+##
+##  CFLAGS += -I/usr/local/include
+##  LFLAGS += -L/usr/local/lib

+ 107 - 0
sources/mtl/template.mk

@@ -0,0 +1,107 @@
+##
+##  Template makefile for Standard, Profile, Debug, Release, and Release-static versions
+##
+##    eg: "make rs" for a statically linked release version.
+##        "make d"  for a debug version (no optimizations).
+##        "make"    for the standard version (optimized, but with debug information and assertions active)
+
+PWD        = $(shell pwd)
+EXEC      ?= $(notdir $(PWD))
+
+CSRCS      = $(wildcard $(PWD)/*.cc) 
+DSRCS      = $(foreach dir, $(DEPDIR), $(filter-out $(MROOT)/$(dir)/Main.cc, $(wildcard $(MROOT)/$(dir)/*.cc)))
+CHDRS      = $(wildcard $(PWD)/*.h)
+COBJS      = $(CSRCS:.cc=.o) $(DSRCS:.cc=.o)
+
+PCOBJS     = $(addsuffix p,  $(COBJS))
+DCOBJS     = $(addsuffix d,  $(COBJS))
+RCOBJS     = $(addsuffix r,  $(COBJS))
+
+
+CXX       ?= g++
+CFLAGS    ?= -Wall -Wno-parentheses --std=c++0x
+LFLAGS    ?= -Wall --std=c++0x
+
+COPTIMIZE ?= -O3
+
+CFLAGS    += -I$(MROOT) -D __STDC_LIMIT_MACROS -D __STDC_FORMAT_MACROS
+LFLAGS    += -lz
+
+.PHONY : s p d r rs clean 
+
+s:	$(EXEC)
+p:	$(EXEC)_profile
+d:	$(EXEC)_debug
+r:	$(EXEC)_release
+rs:	$(EXEC)_static
+
+libs:	lib$(LIB)_standard.a
+libp:	lib$(LIB)_profile.a
+libd:	lib$(LIB)_debug.a
+libr:	lib$(LIB)_release.a
+
+## Compile options
+%.o:			CFLAGS +=$(COPTIMIZE) -g -D DEBUG
+%.op:			CFLAGS +=$(COPTIMIZE) -pg -g -D NDEBUG
+%.od:			CFLAGS +=-O0 -g -D DEBUG
+%.or:			CFLAGS +=$(COPTIMIZE) -g -D NDEBUG
+
+## Link options
+$(EXEC):		LFLAGS += -g
+$(EXEC)_profile:	LFLAGS += -g -pg
+$(EXEC)_debug:		LFLAGS += -g
+#$(EXEC)_release:	LFLAGS += ...
+$(EXEC)_static:		LFLAGS += --static
+
+## Dependencies
+$(EXEC):		$(COBJS)
+$(EXEC)_profile:	$(PCOBJS)
+$(EXEC)_debug:		$(DCOBJS)
+$(EXEC)_release:	$(RCOBJS)
+$(EXEC)_static:		$(RCOBJS)
+
+lib$(LIB)_standard.a:	$(filter-out */Main.o,  $(COBJS))
+lib$(LIB)_profile.a:	$(filter-out */Main.op, $(PCOBJS))
+lib$(LIB)_debug.a:	$(filter-out */Main.od, $(DCOBJS))
+lib$(LIB)_release.a:	$(filter-out */Main.or, $(RCOBJS))
+
+
+## Build rule
+%.o %.op %.od %.or:	%.cc
+	@echo Compiling: $(subst $(MROOT)/,,$@)
+	@$(CXX) $(CFLAGS) -c -o $@ $<
+
+## Linking rules (standard/profile/debug/release)
+$(EXEC) $(EXEC)_profile $(EXEC)_debug $(EXEC)_release $(EXEC)_static:
+	@echo Linking: "$@ ( $(foreach f,$^,$(subst $(MROOT)/,,$f)) )"
+	@$(CXX) $^ $(LFLAGS) -o $@
+
+## Library rules (standard/profile/debug/release)
+lib$(LIB)_standard.a lib$(LIB)_profile.a lib$(LIB)_release.a lib$(LIB)_debug.a:
+	@echo Making library: "$@ ( $(foreach f,$^,$(subst $(MROOT)/,,$f)) )"
+	@$(AR) -rcsv $@ $^
+
+## Library Soft Link rule:
+libs libp libd libr:
+	@echo "Making Soft Link: $^ -> lib$(LIB).a"
+	@ln -sf $^ lib$(LIB).a
+
+## Clean rule
+clean:
+	@rm -f $(EXEC) $(EXEC)_profile $(EXEC)_debug $(EXEC)_release $(EXEC)_static \
+	  $(COBJS) $(PCOBJS) $(DCOBJS) $(RCOBJS) *.core depend.mk 
+
+## Make dependencies
+depend.mk: $(CSRCS) $(CHDRS)
+	@echo Making dependencies
+	@$(CXX) $(CFLAGS) -I$(MROOT) \
+	   $(CSRCS) -MM | sed 's|\(.*\):|$(PWD)/\1 $(PWD)/\1r $(PWD)/\1d $(PWD)/\1p:|' > depend.mk
+	@for dir in $(DEPDIR); do \
+	      if [ -r $(MROOT)/$${dir}/depend.mk ]; then \
+		  echo Depends on: $${dir}; \
+		  cat $(MROOT)/$${dir}/depend.mk >> depend.mk; \
+	      fi; \
+	  done
+
+-include $(MROOT)/mtl/config.mk
+-include depend.mk

+ 268 - 0
sources/simp/Main.cc

@@ -0,0 +1,268 @@
+/*****************************************************************************************[Main.cc]
+Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2007,      Niklas Sorensson
+
+ Chanseok Oh's MiniSat Patch Series -- Copyright (c) 2015, Chanseok Oh
+ 
+Maple_LCM, Based on MapleCOMSPS_DRUP -- Copyright (c) 2017, Mao Luo, Chu-Min LI, Fan Xiao: implementing a learnt clause minimisation approach
+Reference: M. Luo, C.-M. Li, F. Xiao, F. Manya, and Z. L. , “An effective learnt clause minimization approach for cdcl sat solvers,” in IJCAI-2017, 2017, pp. to–appear.
+ 
+Maple_LCM_Dist, Based on Maple_LCM -- Copyright (c) 2017, Fan Xiao, Chu-Min LI, Mao Luo: using a new branching heuristic called Distance at the beginning of search
+ 
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#include <errno.h>
+
+#include <signal.h>
+#include <zlib.h>
+#include <sys/resource.h>
+
+#include "utils/System.h"
+#include "utils/ParseUtils.h"
+#include "utils/Options.h"
+#include "core/Dimacs.h"
+#include "simp/SimpSolver.h"
+
+using namespace Minisat;
+
+//=================================================================================================
+
+
+void printStats(Solver& solver)
+{
+    double cpu_time = cpuTime();
+    double mem_used = memUsedPeak();
+    printf("c restarts              : %"PRIu64"\n", solver.starts);
+    printf("c conflicts             : %-12"PRIu64"   (%.0f /sec)\n", solver.conflicts   , solver.conflicts   /cpu_time);
+    printf("c decisions             : %-12"PRIu64"   (%4.2f %% random) (%.0f /sec)\n", solver.decisions, (float)solver.rnd_decisions*100 / (float)solver.decisions, solver.decisions   /cpu_time);
+    printf("c propagations          : %-12"PRIu64"   (%.0f /sec)\n", solver.propagations, solver.propagations/cpu_time);
+    printf("c conflict literals     : %-12"PRIu64"   (%4.2f %% deleted)\n", solver.tot_literals, (solver.max_literals - solver.tot_literals)*100 / (double)solver.max_literals);
+    if (mem_used != 0) printf("c Memory used           : %.2f MB\n", mem_used);
+    printf("c CPU time              : %g s\n", cpu_time);
+}
+
+
+static Solver* solver;
+// Terminate by notifying the solver and back out gracefully. This is mainly to have a test-case
+// for this feature of the Solver as it may take longer than an immediate call to '_exit()'.
+static void SIGINT_interrupt(int signum) { solver->interrupt(); }
+
+// Note that '_exit()' rather than 'exit()' has to be used. The reason is that 'exit()' calls
+// destructors and may cause deadlocks if a malloc/free function happens to be running (these
+// functions are guarded by locks for multithreaded use).
+static void SIGINT_exit(int signum) {
+    printf("\n"); printf("c *** INTERRUPTED ***\n");
+    if (solver->verbosity > 0){
+        printStats(*solver);
+        printf("\n"); printf("c *** INTERRUPTED ***\n"); }
+    _exit(1); }
+
+
+//=================================================================================================
+// Main:
+
+int main(int argc, char** argv)
+{
+    try {
+        setUsageHelp("USAGE: %s [options] <input-file> <result-output-file>\n\n  where input may be either in plain or gzipped DIMACS.\n");
+        printf("c This is COMiniSatPS.\n");
+        
+#if defined(__linux__)
+        fpu_control_t oldcw, newcw;
+        _FPU_GETCW(oldcw); newcw = (oldcw & ~_FPU_EXTENDED) | _FPU_DOUBLE; _FPU_SETCW(newcw);
+        printf("c WARNING: for repeatability, setting FPU to use double precision\n");
+#endif
+        // Extra options:
+        //
+        IntOption    verb   ("MAIN", "verb",   "Verbosity level (0=silent, 1=some, 2=more).", 1, IntRange(0, 2));
+        BoolOption   pre    ("MAIN", "pre",    "Completely turn on/off any preprocessing.", true);
+        StringOption dimacs ("MAIN", "dimacs", "If given, stop after preprocessing and write the result to this file.");
+        IntOption    cpu_lim("MAIN", "cpu-lim","Limit on CPU time allowed in seconds.\n", INT32_MAX, IntRange(0, INT32_MAX));
+        IntOption    mem_lim("MAIN", "mem-lim","Limit on memory usage in megabytes.\n", INT32_MAX, IntRange(0, INT32_MAX));
+        BoolOption   drup   ("MAIN", "drup",   "Generate DRUP UNSAT proof.", false);
+        StringOption drup_file("MAIN", "drup-file", "DRUP UNSAT proof ouput file.", "/dev/null");
+
+        parseOptions(argc, argv, true);
+        
+        SimpSolver  S;
+        double      initial_time = cpuTime();
+
+        if (!pre) S.eliminate(true);
+
+        S.parsing = true;
+        S.verbosity = verb;
+        if (drup || strlen(drup_file)){
+            S.drup_file = strlen(drup_file) ? fopen(drup_file, "wb") : stdout;
+            if (S.drup_file == NULL){
+                S.drup_file = stdout;
+                printf("c Error opening %s for write.\n", (const char*) drup_file); }
+            printf("c DRUP proof generation: %s\n", S.drup_file == stdout ? "stdout" : drup_file);
+        }
+
+        solver = &S;
+        // Use signal handlers that forcibly quit until the solver will be able to respond to
+        // interrupts:
+        signal(SIGINT, SIGINT_exit);
+        signal(SIGXCPU,SIGINT_exit);
+
+        // Set limit on CPU-time:
+        if (cpu_lim != INT32_MAX){
+            rlimit rl;
+            getrlimit(RLIMIT_CPU, &rl);
+            if (rl.rlim_max == RLIM_INFINITY || (rlim_t)cpu_lim < rl.rlim_max){
+                rl.rlim_cur = cpu_lim;
+                if (setrlimit(RLIMIT_CPU, &rl) == -1)
+                    printf("c WARNING! Could not set resource limit: CPU-time.\n");
+            } }
+
+        // Set limit on virtual memory:
+        if (mem_lim != INT32_MAX){
+            rlim_t new_mem_lim = (rlim_t)mem_lim * 1024*1024;
+            rlimit rl;
+            getrlimit(RLIMIT_AS, &rl);
+            if (rl.rlim_max == RLIM_INFINITY || new_mem_lim < rl.rlim_max){
+                rl.rlim_cur = new_mem_lim;
+                if (setrlimit(RLIMIT_AS, &rl) == -1)
+                    printf("c WARNING! Could not set resource limit: Virtual memory.\n");
+            } }
+        
+        if (argc == 1)
+            printf("c Reading from standard input... Use '--help' for help.\n");
+
+        gzFile in = (argc == 1) ? gzdopen(0, "rb") : gzopen(argv[1], "rb");
+        if (in == NULL)
+            printf("c ERROR! Could not open file: %s\n", argc == 1 ? "<stdin>" : argv[1]), exit(1);
+        
+        if (S.verbosity > 0){
+            printf("c ============================[ Problem Statistics ]=============================\n");
+            printf("c |                                                                             |\n"); }
+        
+        parse_DIMACS(in, S);
+        gzclose(in);
+        FILE* res = (argc >= 3) ? fopen(argv[2], "wb") : NULL;
+
+        if (S.verbosity > 0){
+            printf("c |  Number of variables:  %12d                                         |\n", S.nVars());
+            printf("c |  Number of clauses:    %12d                                         |\n", S.nClauses()); }
+        
+        double parsed_time = cpuTime();
+        if (S.verbosity > 0)
+            printf("c |  Parse time:           %12.2f s                                       |\n", parsed_time - initial_time);
+
+        // Change to signal-handlers that will only notify the solver and allow it to terminate
+        // voluntarily:
+        signal(SIGINT, SIGINT_interrupt);
+        signal(SIGXCPU,SIGINT_interrupt);
+
+        S.parsing = false;
+        S.eliminate(true);
+        double simplified_time = cpuTime();
+        if (S.verbosity > 0){
+            printf("c |  Simplification time:  %12.2f s                                       |\n", simplified_time - parsed_time);
+            printf("c |                                                                             |\n"); }
+
+        if (!S.okay()){
+            if (res != NULL) fprintf(res, "UNSAT\n"), fclose(res);
+            if (S.verbosity > 0){
+                printf("c ===============================================================================\n");
+                printf("c Solved by simplification\n");
+                printStats(S);
+                printf("\n"); }
+            printf("s UNSATISFIABLE\n");
+            if (S.drup_file){
+#ifdef BIN_DRUP
+                fputc('a', S.drup_file); fputc(0, S.drup_file);
+#else
+                fprintf(S.drup_file, "0\n");
+#endif
+            }
+            if (S.drup_file && S.drup_file != stdout) fclose(S.drup_file);
+            exit(20);
+        }
+
+        if (dimacs){
+            if (S.verbosity > 0)
+                printf("c ==============================[ Writing DIMACS ]===============================\n");
+            S.toDimacs((const char*)dimacs);
+            if (S.verbosity > 0)
+                printStats(S);
+            exit(0);
+        }
+
+        vec<Lit> dummy;
+        lbool ret = S.solveLimited(dummy);
+        
+        if (S.verbosity > 0){
+            printStats(S);
+            printf("\n"); }
+        printf(ret == l_True ? "s SATISFIABLE\n" : ret == l_False ? "s UNSATISFIABLE\n" : "s UNKNOWN\n");
+        if (ret == l_True){
+            printf("v ");
+            for (int i = 0; i < S.nVars(); i++)
+                if (S.model[i] != l_Undef)
+                    printf("%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1);
+            printf(" 0\n");
+            //----------------------
+            //printf("c solvedBy  : ");if(S.solvedByUncom) printf("UnCom\n"); else printf("Com\n");
+            //=====================
+        }
+        //------------------------------------------
+        //printf("c UncomTime : %lf\n",S.UnComTime);
+        //printf("c UncomNum  : %d\n",S.callNum);
+        //=========================================
+        if (S.drup_file && ret == l_False){
+#ifdef BIN_DRUP
+            fputc('a', S.drup_file); fputc(0, S.drup_file);
+#else
+            fprintf(S.drup_file, "0\n");
+#endif
+        }
+        if (S.drup_file && S.drup_file != stdout) fclose(S.drup_file);
+
+        if (res != NULL){
+            if (ret == l_True){
+                fprintf(res, "SAT\n");
+                for (int i = 0; i < S.nVars(); i++)
+                    if (S.model[i] != l_Undef)
+                        fprintf(res, "%s%s%d", (i==0)?"":" ", (S.model[i]==l_True)?"":"-", i+1);
+                fprintf(res, " 0\n");
+            }else if (ret == l_False)
+                fprintf(res, "UNSAT\n");
+            else
+                fprintf(res, "INDET\n");
+            //--------------------------
+            //fprintf(res,"c solvedBy  : ");if(S.solvedByUncom) fprintf(res,"UnCom\n"); else fprintf(res,"Com\n");
+            //fprintf(res,"c UncomTime : %lf\n",S.UnComTime);
+            //fprintf(res,"c TotalTime : %lf\n",cpuTime());
+            //fprintf(res,"c UncomNum  : %d\n",S.callNum);
+            //==========================
+            fclose(res);
+        }
+
+#ifdef NDEBUG
+        exit(ret == l_True ? 10 : ret == l_False ? 20 : 0);     // (faster than "return", which will invoke the destructor for 'Solver')
+#else
+        return (ret == l_True ? 10 : ret == l_False ? 20 : 0);
+#endif
+    } catch (OutOfMemoryException&){
+        printf("c ===============================================================================\n");
+        printf("c Out of memory\n");
+        printf("s UNKNOWN\n");
+        exit(0);
+    }
+}

+ 5 - 0
sources/simp/Makefile

@@ -0,0 +1,5 @@
+EXEC      = ReasonLS
+DEPDIR    = mtl utils core
+MROOT     = ../
+
+include $(MROOT)/mtl/template.mk

+ 831 - 0
sources/simp/SimpSolver.cc

@@ -0,0 +1,831 @@
+/***********************************************************************************[SimpSolver.cc]
+MiniSat -- Copyright (c) 2006,      Niklas Een, Niklas Sorensson
+           Copyright (c) 2007-2010, Niklas Sorensson
+
+Chanseok Oh's MiniSat Patch Series -- Copyright (c) 2015, Chanseok Oh
+ 
+Maple_LCM, Based on MapleCOMSPS_DRUP -- Copyright (c) 2017, Mao Luo, Chu-Min LI, Fan Xiao: implementing a learnt clause minimisation approach
+Reference: M. Luo, C.-M. Li, F. Xiao, F. Manya, and Z. L. , “An effective learnt clause minimization approach for cdcl sat solvers,” in IJCAI-2017, 2017, pp. to–appear.
+ 
+Maple_LCM_Dist, Based on Maple_LCM -- Copyright (c) 2017, Fan Xiao, Chu-Min LI, Mao Luo: using a new branching heuristic called Distance at the beginning of search
+ 
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#include "mtl/Sort.h"
+#include "simp/SimpSolver.h"
+#include "utils/System.h"
+
+using namespace Minisat;
+
+//=================================================================================================
+// Options:
+
+
+static const char* _cat = "SIMP";
+
+static BoolOption   opt_use_asymm        (_cat, "asymm",        "Shrink clauses by asymmetric branching.", false);
+static BoolOption   opt_use_rcheck       (_cat, "rcheck",       "Check if a clause is already implied. (costly)", false);
+static BoolOption   opt_use_elim         (_cat, "elim",         "Perform variable elimination.", true);
+static IntOption    opt_grow             (_cat, "grow",         "Allow a variable elimination step to grow by a number of clauses.", 0);
+static IntOption    opt_clause_lim       (_cat, "cl-lim",       "Variables are not eliminated if it produces a resolvent with a length above this limit. -1 means no limit", 20,   IntRange(-1, INT32_MAX));
+static IntOption    opt_subsumption_lim  (_cat, "sub-lim",      "Do not check if subsumption against a clause larger than this. -1 means no limit.", 1000, IntRange(-1, INT32_MAX));
+static DoubleOption opt_simp_garbage_frac(_cat, "simp-gc-frac", "The fraction of wasted memory allowed before a garbage collection is triggered during simplification.",  0.5, DoubleRange(0, false, HUGE_VAL, false));
+
+
+//=================================================================================================
+// Constructor/Destructor:
+
+
+SimpSolver::SimpSolver() :
+    parsing            (false)
+  , grow               (opt_grow)
+  , clause_lim         (opt_clause_lim)
+  , subsumption_lim    (opt_subsumption_lim)
+  , simp_garbage_frac  (opt_simp_garbage_frac)
+  , use_asymm          (opt_use_asymm)
+  , use_rcheck         (opt_use_rcheck)
+  , use_elim           (opt_use_elim)
+  , merges             (0)
+  , asymm_lits         (0)
+  , eliminated_vars    (0)
+  , elimorder          (1)
+  , use_simplification (true)
+  , occurs             (ClauseDeleted(ca))
+  , elim_heap          (ElimLt(n_occ))
+  , bwdsub_assigns     (0)
+  , n_touched          (0)
+{
+    vec<Lit> dummy(1,lit_Undef);
+    ca.extra_clause_field = true; // NOTE: must happen before allocating the dummy clause below.
+    bwdsub_tmpunit        = ca.alloc(dummy);
+    remove_satisfied      = false;
+}
+
+
+SimpSolver::~SimpSolver()
+{
+}
+
+
+Var SimpSolver::newVar(bool sign, bool dvar) {
+    Var v = Solver::newVar(sign, dvar);
+
+    frozen    .push((char)false);
+    eliminated.push((char)false);
+
+    if (use_simplification){
+        n_occ     .push(0);
+        n_occ     .push(0);
+        occurs    .init(v);
+        touched   .push(0);
+        elim_heap .insert(v);
+    }
+    return v; }
+
+
+
+lbool SimpSolver::solve_(bool do_simp, bool turn_off_simp)
+{
+    vec<Var> extra_frozen;
+    lbool    result = l_True;
+
+    do_simp &= use_simplification;
+
+    if (do_simp){
+        // Assumptions must be temporarily frozen to run variable elimination:
+        for (int i = 0; i < assumptions.size(); i++){
+            Var v = var(assumptions[i]);
+
+            // If an assumption has been eliminated, remember it.
+            assert(!isEliminated(v));
+
+            if (!frozen[v]){
+                // Freeze and store.
+                setFrozen(v, true);
+                extra_frozen.push(v);
+            } }
+
+        result = lbool(eliminate(turn_off_simp));
+    }
+
+    if (result == l_True)
+        result = Solver::solve_();
+    else if (verbosity >= 1)
+        printf("c ===============================================================================\n");
+
+    if (result == l_True)
+        extendModel();
+
+    if (do_simp)
+        // Unfreeze the assumptions that were frozen:
+        for (int i = 0; i < extra_frozen.size(); i++)
+            setFrozen(extra_frozen[i], false);
+
+    return result;
+}
+
+
+
+bool SimpSolver::addClause_(vec<Lit>& ps)
+{
+#ifndef NDEBUG
+    for (int i = 0; i < ps.size(); i++)
+        assert(!isEliminated(var(ps[i])));
+#endif
+
+    int nclauses = clauses.size();
+
+    if (use_rcheck && implied(ps))
+        return true;
+
+    if (!Solver::addClause_(ps))
+        return false;
+
+    if (!parsing && drup_file) {
+#ifdef BIN_DRUP
+        binDRUP('a', ps, drup_file);
+#else
+        for (int i = 0; i < ps.size(); i++)
+            fprintf(drup_file, "%i ", (var(ps[i]) + 1) * (-2 * sign(ps[i]) + 1));
+        fprintf(drup_file, "0\n");
+#endif
+    }
+
+    if (use_simplification && clauses.size() == nclauses + 1){
+        CRef          cr = clauses.last();
+        const Clause& c  = ca[cr];
+
+        // NOTE: the clause is added to the queue immediately and then
+        // again during 'gatherTouchedClauses()'. If nothing happens
+        // in between, it will only be checked once. Otherwise, it may
+        // be checked twice unnecessarily. This is an unfortunate
+        // consequence of how backward subsumption is used to mimic
+        // forward subsumption.
+        subsumption_queue.insert(cr);
+        for (int i = 0; i < c.size(); i++){
+            occurs[var(c[i])].push(cr);
+            n_occ[toInt(c[i])]++;
+            touched[var(c[i])] = 1;
+            n_touched++;
+            if (elim_heap.inHeap(var(c[i])))
+                elim_heap.increase(var(c[i]));
+        }
+    }
+
+    return true;
+}
+
+
+void SimpSolver::removeClause(CRef cr)
+{
+    const Clause& c = ca[cr];
+
+    if (use_simplification)
+        for (int i = 0; i < c.size(); i++){
+            n_occ[toInt(c[i])]--;
+            updateElimHeap(var(c[i]));
+            occurs.smudge(var(c[i]));
+        }
+
+    Solver::removeClause(cr);
+}
+
+
+bool SimpSolver::strengthenClause(CRef cr, Lit l)
+{
+    Clause& c = ca[cr];
+    assert(decisionLevel() == 0);
+    assert(use_simplification);
+
+    // FIX: this is too inefficient but would be nice to have (properly implemented)
+    // if (!find(subsumption_queue, &c))
+    subsumption_queue.insert(cr);
+
+    if (drup_file){
+#ifdef BIN_DRUP
+        binDRUP_strengthen(c, l, drup_file);
+#else
+        for (int i = 0; i < c.size(); i++)
+            if (c[i] != l) fprintf(drup_file, "%i ", (var(c[i]) + 1) * (-2 * sign(c[i]) + 1));
+        fprintf(drup_file, "0\n");
+#endif
+    }
+
+    if (c.size() == 2){
+        removeClause(cr);
+        c.strengthen(l);
+    }else{
+        if (drup_file){
+#ifdef BIN_DRUP
+            binDRUP('d', c, drup_file);
+#else
+            fprintf(drup_file, "d ");
+            for (int i = 0; i < c.size(); i++)
+                fprintf(drup_file, "%i ", (var(c[i]) + 1) * (-2 * sign(c[i]) + 1));
+            fprintf(drup_file, "0\n");
+#endif
+        }
+
+        detachClause(cr, true);
+        c.strengthen(l);
+        attachClause(cr);
+        remove(occurs[var(l)], cr);
+        n_occ[toInt(l)]--;
+        updateElimHeap(var(l));
+    }
+
+    return c.size() == 1 ? enqueue(c[0]) && propagate() == CRef_Undef : true;
+}
+
+
+// Returns FALSE if clause is always satisfied ('out_clause' should not be used).
+bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause)
+{
+    merges++;
+    out_clause.clear();
+
+    bool  ps_smallest = _ps.size() < _qs.size();
+    const Clause& ps  =  ps_smallest ? _qs : _ps;
+    const Clause& qs  =  ps_smallest ? _ps : _qs;
+
+    for (int i = 0; i < qs.size(); i++){
+        if (var(qs[i]) != v){
+            for (int j = 0; j < ps.size(); j++)
+                if (var(ps[j]) == var(qs[i]))
+                    if (ps[j] == ~qs[i])
+                        return false;
+                    else
+                        goto next;
+            out_clause.push(qs[i]);
+        }
+        next:;
+    }
+
+    for (int i = 0; i < ps.size(); i++)
+        if (var(ps[i]) != v)
+            out_clause.push(ps[i]);
+
+    return true;
+}
+
+
+// Returns FALSE if clause is always satisfied.
+bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, int& size)
+{
+    merges++;
+
+    bool  ps_smallest = _ps.size() < _qs.size();
+    const Clause& ps  =  ps_smallest ? _qs : _ps;
+    const Clause& qs  =  ps_smallest ? _ps : _qs;
+    const Lit*  __ps  = (const Lit*)ps;
+    const Lit*  __qs  = (const Lit*)qs;
+
+    size = ps.size()-1;
+
+    for (int i = 0; i < qs.size(); i++){
+        if (var(__qs[i]) != v){
+            for (int j = 0; j < ps.size(); j++)
+                if (var(__ps[j]) == var(__qs[i]))
+                    if (__ps[j] == ~__qs[i])
+                        return false;
+                    else
+                        goto next;
+            size++;
+        }
+        next:;
+    }
+
+    return true;
+}
+
+
+void SimpSolver::gatherTouchedClauses()
+{
+    if (n_touched == 0) return;
+
+    int i,j;
+    for (i = j = 0; i < subsumption_queue.size(); i++)
+        if (ca[subsumption_queue[i]].mark() == 0)
+            ca[subsumption_queue[i]].mark(2);
+
+    for (i = 0; i < touched.size(); i++)
+        if (touched[i]){
+            const vec<CRef>& cs = occurs.lookup(i);
+            for (j = 0; j < cs.size(); j++)
+                if (ca[cs[j]].mark() == 0){
+                    subsumption_queue.insert(cs[j]);
+                    ca[cs[j]].mark(2);
+                }
+            touched[i] = 0;
+        }
+
+    for (i = 0; i < subsumption_queue.size(); i++)
+        if (ca[subsumption_queue[i]].mark() == 2)
+            ca[subsumption_queue[i]].mark(0);
+
+    n_touched = 0;
+}
+
+
+bool SimpSolver::implied(const vec<Lit>& c)
+{
+    assert(decisionLevel() == 0);
+
+    trail_lim.push(trail.size());
+    for (int i = 0; i < c.size(); i++)
+        if (value(c[i]) == l_True){
+            cancelUntil(0);
+            return true;
+        }else if (value(c[i]) != l_False){
+            assert(value(c[i]) == l_Undef);
+            uncheckedEnqueue(~c[i]);
+        }
+
+    bool result = propagate() != CRef_Undef;
+    cancelUntil(0);
+    return result;
+}
+
+
+// Backward subsumption + backward subsumption resolution
+bool SimpSolver::backwardSubsumptionCheck(bool verbose)
+{
+    int cnt = 0;
+    int subsumed = 0;
+    int deleted_literals = 0;
+    assert(decisionLevel() == 0);
+
+    while (subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()){
+
+        // Empty subsumption queue and return immediately on user-interrupt:
+        if (asynch_interrupt){
+            subsumption_queue.clear();
+            bwdsub_assigns = trail.size();
+            break; }
+
+        // Check top-level assignments by creating a dummy clause and placing it in the queue:
+        if (subsumption_queue.size() == 0 && bwdsub_assigns < trail.size()){
+            Lit l = trail[bwdsub_assigns++];
+            ca[bwdsub_tmpunit][0] = l;
+            ca[bwdsub_tmpunit].calcAbstraction();
+            subsumption_queue.insert(bwdsub_tmpunit); }
+
+        CRef    cr = subsumption_queue.peek(); subsumption_queue.pop();
+        Clause& c  = ca[cr];
+
+        if (c.mark()) continue;
+
+        if (verbose && verbosity >= 2 && cnt++ % 1000 == 0)
+            printf("c subsumption left: %10d (%10d subsumed, %10d deleted literals)\r", subsumption_queue.size(), subsumed, deleted_literals);
+
+        assert(c.size() > 1 || value(c[0]) == l_True);    // Unit-clauses should have been propagated before this point.
+
+        // Find best variable to scan:
+        Var best = var(c[0]);
+        for (int i = 1; i < c.size(); i++)
+            if (occurs[var(c[i])].size() < occurs[best].size())
+                best = var(c[i]);
+
+        // Search all candidates:
+        vec<CRef>& _cs = occurs.lookup(best);
+        CRef*       cs = (CRef*)_cs;
+
+        for (int j = 0; j < _cs.size(); j++)
+            if (c.mark())
+                break;
+            else if (!ca[cs[j]].mark() &&  cs[j] != cr && (subsumption_lim == -1 || ca[cs[j]].size() < subsumption_lim)){
+                Lit l = c.subsumes(ca[cs[j]]);
+
+                if (l == lit_Undef)
+                    subsumed++, removeClause(cs[j]);
+                else if (l != lit_Error){
+                    deleted_literals++;
+
+                    if (!strengthenClause(cs[j], ~l))
+                        return false;
+
+                    // Did current candidate get deleted from cs? Then check candidate at index j again:
+                    if (var(l) == best)
+                        j--;
+                }
+            }
+    }
+
+    return true;
+}
+
+
+bool SimpSolver::asymm(Var v, CRef cr)
+{
+    Clause& c = ca[cr];
+    assert(decisionLevel() == 0);
+
+    if (c.mark() || satisfied(c)) return true;
+
+    trail_lim.push(trail.size());
+    Lit l = lit_Undef;
+    for (int i = 0; i < c.size(); i++)
+        if (var(c[i]) != v){
+            if (value(c[i]) != l_False)
+                uncheckedEnqueue(~c[i]);
+        }else
+            l = c[i];
+
+    if (propagate() != CRef_Undef){
+        cancelUntil(0);
+        asymm_lits++;
+        if (!strengthenClause(cr, l))
+            return false;
+    }else
+        cancelUntil(0);
+
+    return true;
+}
+
+
+bool SimpSolver::asymmVar(Var v)
+{
+    assert(use_simplification);
+
+    const vec<CRef>& cls = occurs.lookup(v);
+
+    if (value(v) != l_Undef || cls.size() == 0)
+        return true;
+
+    for (int i = 0; i < cls.size(); i++)
+        if (!asymm(v, cls[i]))
+            return false;
+
+    return backwardSubsumptionCheck();
+}
+
+
+static void mkElimClause(vec<uint32_t>& elimclauses, Lit x)
+{
+    elimclauses.push(toInt(x));
+    elimclauses.push(1);
+}
+
+
+static void mkElimClause(vec<uint32_t>& elimclauses, Var v, Clause& c)
+{
+    int first = elimclauses.size();
+    int v_pos = -1;
+
+    // Copy clause to elimclauses-vector. Remember position where the
+    // variable 'v' occurs:
+    for (int i = 0; i < c.size(); i++){
+        elimclauses.push(toInt(c[i]));
+        if (var(c[i]) == v)
+            v_pos = i + first;
+    }
+    assert(v_pos != -1);
+
+    // Swap the first literal with the 'v' literal, so that the literal
+    // containing 'v' will occur first in the clause:
+    uint32_t tmp = elimclauses[v_pos];
+    elimclauses[v_pos] = elimclauses[first];
+    elimclauses[first] = tmp;
+
+    // Store the length of the clause last:
+    elimclauses.push(c.size());
+}
+
+
+
+bool SimpSolver::eliminateVar(Var v)
+{
+    assert(!frozen[v]);
+    assert(!isEliminated(v));
+    assert(value(v) == l_Undef);
+
+    // Split the occurrences into positive and negative:
+    //
+    const vec<CRef>& cls = occurs.lookup(v);
+    vec<CRef>        pos, neg;
+    for (int i = 0; i < cls.size(); i++)
+        (find(ca[cls[i]], mkLit(v)) ? pos : neg).push(cls[i]);
+
+    // Check wether the increase in number of clauses stays within the allowed ('grow'). Moreover, no
+    // clause must exceed the limit on the maximal clause size (if it is set):
+    //
+    int cnt         = 0;
+    int clause_size = 0;
+
+    for (int i = 0; i < pos.size(); i++)
+        for (int j = 0; j < neg.size(); j++)
+            if (merge(ca[pos[i]], ca[neg[j]], v, clause_size) && 
+                (++cnt > cls.size() + grow || (clause_lim != -1 && clause_size > clause_lim)))
+                return true;
+
+    // Delete and store old clauses:
+    eliminated[v] = true;
+    setDecisionVar(v, false);
+    eliminated_vars++;
+
+    if (pos.size() > neg.size()){
+        for (int i = 0; i < neg.size(); i++)
+            mkElimClause(elimclauses, v, ca[neg[i]]);
+        mkElimClause(elimclauses, mkLit(v));
+    }else{
+        for (int i = 0; i < pos.size(); i++)
+            mkElimClause(elimclauses, v, ca[pos[i]]);
+        mkElimClause(elimclauses, ~mkLit(v));
+    }
+
+    // Produce clauses in cross product:
+    vec<Lit>& resolvent = add_tmp;
+    for (int i = 0; i < pos.size(); i++)
+        for (int j = 0; j < neg.size(); j++)
+            if (merge(ca[pos[i]], ca[neg[j]], v, resolvent) && !addClause_(resolvent))
+                return false;
+
+    for (int i = 0; i < cls.size(); i++)
+        removeClause(cls[i]); 
+
+    // Free occurs list for this variable:
+    occurs[v].clear(true);
+    
+    // Free watchers lists for this variable, if possible:
+    watches_bin[ mkLit(v)].clear(true);
+    watches_bin[~mkLit(v)].clear(true);
+    watches[ mkLit(v)].clear(true);
+    watches[~mkLit(v)].clear(true);
+
+    return backwardSubsumptionCheck();
+}
+
+
+bool SimpSolver::substitute(Var v, Lit x)
+{
+    assert(!frozen[v]);
+    assert(!isEliminated(v));
+    assert(value(v) == l_Undef);
+
+    if (!ok) return false;
+
+    eliminated[v] = true;
+    setDecisionVar(v, false);
+    const vec<CRef>& cls = occurs.lookup(v);
+    
+    vec<Lit>& subst_clause = add_tmp;
+    for (int i = 0; i < cls.size(); i++){
+        Clause& c = ca[cls[i]];
+
+        subst_clause.clear();
+        for (int j = 0; j < c.size(); j++){
+            Lit p = c[j];
+            subst_clause.push(var(p) == v ? x ^ sign(p) : p);
+        }
+
+        if (!addClause_(subst_clause))
+            return ok = false;
+
+        removeClause(cls[i]);
+    }
+
+    return true;
+}
+
+
+void SimpSolver::extendModel()
+{
+    int i, j;
+    Lit x;
+
+    for (i = elimclauses.size()-1; i > 0; i -= j){
+        for (j = elimclauses[i--]; j > 1; j--, i--)
+            if (modelValue(toLit(elimclauses[i])) != l_False)
+                goto next;
+
+        x = toLit(elimclauses[i]);
+        model[var(x)] = lbool(!sign(x));
+    next:;
+    }
+}
+
+// Almost duplicate of Solver::removeSatisfied. Didn't want to make the base method 'virtual'.
+void SimpSolver::removeSatisfied()
+{
+    int i, j;
+    for (i = j = 0; i < clauses.size(); i++){
+        const Clause& c = ca[clauses[i]];
+        if (c.mark() == 0)
+            if (satisfied(c))
+                removeClause(clauses[i]);
+            else
+                clauses[j++] = clauses[i];
+    }
+    clauses.shrink(i - j);
+}
+
+// The technique and code are by the courtesy of the GlueMiniSat team. Thank you!
+// It helps solving certain types of huge problems tremendously.
+bool SimpSolver::eliminate(bool turn_off_elim)
+{
+    bool res = true;
+    int iter = 0;
+    int n_cls, n_cls_init, n_vars;
+
+    if (nVars() == 0) goto cleanup; // User disabling preprocessing.
+
+    // Get an initial number of clauses (more accurately).
+    if (trail.size() != 0) removeSatisfied();
+    n_cls_init = nClauses();
+
+    res = eliminate_(); // The first, usual variable elimination of MiniSat.
+    if (!res) goto cleanup;
+
+    n_cls  = nClauses();
+    n_vars = nFreeVars();
+
+    printf("c Reduced to %d vars, %d cls (grow=%d)\n", n_vars, n_cls, grow);
+
+    if ((double)n_cls / n_vars >= 10 || n_vars < 10000){
+        printf("c No iterative elimination performed. (vars=%d, c/v ratio=%.1f)\n", n_vars, (double)n_cls / n_vars);
+        goto cleanup; }
+
+    grow = grow ? grow * 2 : 8;
+    for (; grow < 10000; grow *= 2){
+        // Rebuild elimination variable heap.
+        for (int i = 0; i < clauses.size(); i++){
+            const Clause& c = ca[clauses[i]];
+            for (int j = 0; j < c.size(); j++)
+                if (!elim_heap.inHeap(var(c[j])))
+                    elim_heap.insert(var(c[j]));
+                else
+                    elim_heap.update(var(c[j])); }
+
+        int n_cls_last = nClauses();
+        int n_vars_last = nFreeVars();
+
+        res = eliminate_();
+        if (!res || n_vars_last == nFreeVars()) break;
+        iter++;
+
+        int n_cls_now  = nClauses();
+        int n_vars_now = nFreeVars();
+
+        double cl_inc_rate  = (double)n_cls_now   / n_cls_last;
+        double var_dec_rate = (double)n_vars_last / n_vars_now;
+
+        printf("c Reduced to %d vars, %d cls (grow=%d)\n", n_vars_now, n_cls_now, grow);
+        printf("c cl_inc_rate=%.3f, var_dec_rate=%.3f\n", cl_inc_rate, var_dec_rate);
+
+        if (n_cls_now > n_cls_init || cl_inc_rate > var_dec_rate) break;
+    }
+    printf("c No. effective iterative eliminations: %d\n", iter);
+
+cleanup:
+    touched  .clear(true);
+    occurs   .clear(true);
+    n_occ    .clear(true);
+    elim_heap.clear(true);
+    subsumption_queue.clear(true);
+
+    use_simplification    = false;
+    remove_satisfied      = true;
+    ca.extra_clause_field = false;
+
+    // Force full cleanup (this is safe and desirable since it only happens once):
+    rebuildOrderHeap();
+    garbageCollect();
+
+    return res;
+}
+
+
+bool SimpSolver::eliminate_()
+{
+    if (!simplify())
+        return false;
+    else if (!use_simplification)
+        return true;
+
+    int trail_size_last = trail.size();
+
+    // Main simplification loop:
+    //
+    while (n_touched > 0 || bwdsub_assigns < trail.size() || elim_heap.size() > 0){
+
+        gatherTouchedClauses();
+        // printf("  ## (time = %6.2f s) BWD-SUB: queue = %d, trail = %d\n", cpuTime(), subsumption_queue.size(), trail.size() - bwdsub_assigns);
+        if ((subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()) && 
+            !backwardSubsumptionCheck(true)){
+            ok = false; goto cleanup; }
+
+        // Empty elim_heap and return immediately on user-interrupt:
+        if (asynch_interrupt){
+            assert(bwdsub_assigns == trail.size());
+            assert(subsumption_queue.size() == 0);
+            assert(n_touched == 0);
+            elim_heap.clear();
+            goto cleanup; }
+
+        // printf("  ## (time = %6.2f s) ELIM: vars = %d\n", cpuTime(), elim_heap.size());
+        for (int cnt = 0; !elim_heap.empty(); cnt++){
+            Var elim = elim_heap.removeMin();
+            
+            if (asynch_interrupt) break;
+
+            if (isEliminated(elim) || value(elim) != l_Undef) continue;
+
+            if (verbosity >= 2 && cnt % 100 == 0)
+                printf("c elimination left: %10d\r", elim_heap.size());
+
+            if (use_asymm){
+                // Temporarily freeze variable. Otherwise, it would immediately end up on the queue again:
+                bool was_frozen = frozen[elim];
+                frozen[elim] = true;
+                if (!asymmVar(elim)){
+                    ok = false; goto cleanup; }
+                frozen[elim] = was_frozen; }
+
+            // At this point, the variable may have been set by assymetric branching, so check it
+            // again. Also, don't eliminate frozen variables:
+            if (use_elim && value(elim) == l_Undef && !frozen[elim] && !eliminateVar(elim)){
+                ok = false; goto cleanup; }
+
+            checkGarbage(simp_garbage_frac);
+        }
+
+        assert(subsumption_queue.size() == 0);
+    }
+ cleanup:
+    // To get an accurate number of clauses.
+    if (trail_size_last != trail.size())
+        removeSatisfied();
+    else{
+        int i,j;
+        for (i = j = 0; i < clauses.size(); i++)
+            if (ca[clauses[i]].mark() == 0)
+                clauses[j++] = clauses[i];
+        clauses.shrink(i - j);
+    }
+    checkGarbage();
+
+    if (verbosity >= 1 && elimclauses.size() > 0)
+        printf("c |  Eliminated clauses:     %10.2f Mb                                      |\n", 
+               double(elimclauses.size() * sizeof(uint32_t)) / (1024*1024));
+
+    return ok;
+}
+
+
+//=================================================================================================
+// Garbage Collection methods:
+
+
+void SimpSolver::relocAll(ClauseAllocator& to)
+{
+    if (!use_simplification) return;
+
+    // All occurs lists:
+    //
+    occurs.cleanAll();
+    for (int i = 0; i < nVars(); i++){
+        vec<CRef>& cs = occurs[i];
+        for (int j = 0; j < cs.size(); j++)
+            ca.reloc(cs[j], to);
+    }
+
+    // Subsumption queue:
+    //
+    for (int i = 0; i < subsumption_queue.size(); i++)
+        ca.reloc(subsumption_queue[i], to);
+
+    // Temporary clause:
+    //
+    ca.reloc(bwdsub_tmpunit, to);
+}
+
+
+void SimpSolver::garbageCollect()
+{
+    // Initialize the next region to a size corresponding to the estimated utilization degree. This
+    // is not precise but should avoid some unnecessary reallocations for the new region:
+    ClauseAllocator to(ca.size() - ca.wasted()); 
+
+    to.extra_clause_field = ca.extra_clause_field; // NOTE: this is important to keep (or lose) the extra fields.
+    relocAll(to);
+    Solver::relocAll(to);
+    if (verbosity >= 2)
+        printf("c |  Garbage collection:   %12d bytes => %12d bytes             |\n", 
+               ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size);
+    to.moveTo(ca);
+}

+ 207 - 0
sources/simp/SimpSolver.h

@@ -0,0 +1,207 @@
+/************************************************************************************[SimpSolver.h]
+MiniSat -- Copyright (c) 2006,      Niklas Een, Niklas Sorensson
+           Copyright (c) 2007-2010, Niklas Sorensson
+
+Chanseok Oh's MiniSat Patch Series -- Copyright (c) 2015, Chanseok Oh
+ 
+Maple_LCM, Based on MapleCOMSPS_DRUP -- Copyright (c) 2017, Mao Luo, Chu-Min LI, Fan Xiao: implementing a learnt clause minimisation approach
+Reference: M. Luo, C.-M. Li, F. Xiao, F. Manya, and Z. L. , “An effective learnt clause minimization approach for cdcl sat solvers,” in IJCAI-2017, 2017, pp. to–appear.
+
+Maple_LCM_Dist, Based on Maple_LCM -- Copyright (c) 2017, Fan Xiao, Chu-Min LI, Mao Luo: using a new branching heuristic called Distance at the beginning of search
+ 
+ 
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_SimpSolver_h
+#define Minisat_SimpSolver_h
+
+#include "mtl/Queue.h"
+#include "core/Solver.h"
+
+
+namespace Minisat {
+
+//=================================================================================================
+
+
+class SimpSolver : public Solver {
+ public:
+    // Constructor/Destructor:
+    //
+    SimpSolver();
+    ~SimpSolver();
+
+    // Problem specification:
+    //
+    Var     newVar    (bool polarity = true, bool dvar = true);
+    bool    addClause (const vec<Lit>& ps);
+    bool    addEmptyClause();                // Add the empty clause to the solver.
+    bool    addClause (Lit p);               // Add a unit clause to the solver.
+    bool    addClause (Lit p, Lit q);        // Add a binary clause to the solver.
+    bool    addClause (Lit p, Lit q, Lit r); // Add a ternary clause to the solver.
+    bool    addClause_(      vec<Lit>& ps);
+    bool    substitute(Var v, Lit x);  // Replace all occurences of v with x (may cause a contradiction).
+
+    // Variable mode:
+    // 
+    void    setFrozen (Var v, bool b); // If a variable is frozen it will not be eliminated.
+    bool    isEliminated(Var v) const;
+
+    // Solving:
+    //
+    bool    solve       (const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
+    lbool   solveLimited(const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
+    bool    solve       (                     bool do_simp = true, bool turn_off_simp = false);
+    bool    solve       (Lit p       ,        bool do_simp = true, bool turn_off_simp = false);       
+    bool    solve       (Lit p, Lit q,        bool do_simp = true, bool turn_off_simp = false);
+    bool    solve       (Lit p, Lit q, Lit r, bool do_simp = true, bool turn_off_simp = false);
+    bool    eliminate   (bool turn_off_elim = false);  // Perform variable elimination based simplification. 
+    bool    eliminate_  ();
+    void    removeSatisfied();
+
+    // Memory managment:
+    //
+    virtual void garbageCollect();
+
+
+    // Generate a (possibly simplified) DIMACS file:
+    //
+#if 0
+    void    toDimacs  (const char* file, const vec<Lit>& assumps);
+    void    toDimacs  (const char* file);
+    void    toDimacs  (const char* file, Lit p);
+    void    toDimacs  (const char* file, Lit p, Lit q);
+    void    toDimacs  (const char* file, Lit p, Lit q, Lit r);
+#endif
+
+    // Mode of operation:
+    //
+    bool    parsing;
+    int     grow;              // Allow a variable elimination step to grow by a number of clauses (default to zero).
+    int     clause_lim;        // Variables are not eliminated if it produces a resolvent with a length above this limit.
+                               // -1 means no limit.
+    int     subsumption_lim;   // Do not check if subsumption against a clause larger than this. -1 means no limit.
+    double  simp_garbage_frac; // A different limit for when to issue a GC during simplification (Also see 'garbage_frac').
+
+    bool    use_asymm;         // Shrink clauses by asymmetric branching.
+    bool    use_rcheck;        // Check if a clause is already implied. Prett costly, and subsumes subsumptions :)
+    bool    use_elim;          // Perform variable elimination.
+
+    // Statistics:
+    //
+    int     merges;
+    int     asymm_lits;
+    int     eliminated_vars;
+
+ protected:
+
+    // Helper structures:
+    //
+    struct ElimLt {
+        const vec<int>& n_occ;
+        explicit ElimLt(const vec<int>& no) : n_occ(no) {}
+
+        // TODO: are 64-bit operations here noticably bad on 32-bit platforms? Could use a saturating
+        // 32-bit implementation instead then, but this will have to do for now.
+        uint64_t cost  (Var x)        const { return (uint64_t)n_occ[toInt(mkLit(x))] * (uint64_t)n_occ[toInt(~mkLit(x))]; }
+        bool operator()(Var x, Var y) const { return cost(x) < cost(y); }
+        
+        // TODO: investigate this order alternative more.
+        // bool operator()(Var x, Var y) const { 
+        //     int c_x = cost(x);
+        //     int c_y = cost(y);
+        //     return c_x < c_y || c_x == c_y && x < y; }
+    };
+
+    struct ClauseDeleted {
+        const ClauseAllocator& ca;
+        explicit ClauseDeleted(const ClauseAllocator& _ca) : ca(_ca) {}
+        bool operator()(const CRef& cr) const { return ca[cr].mark() == 1; } };
+
+    // Solver state:
+    //
+    int                 elimorder;
+    bool                use_simplification;
+    vec<uint32_t>       elimclauses;
+    vec<char>           touched;
+    OccLists<Var, vec<CRef>, ClauseDeleted>
+                        occurs;
+    vec<int>            n_occ;
+    Heap<ElimLt>        elim_heap;
+    Queue<CRef>         subsumption_queue;
+    vec<char>           frozen;
+    vec<char>           eliminated;
+    int                 bwdsub_assigns;
+    int                 n_touched;
+
+    // Temporaries:
+    //
+    CRef                bwdsub_tmpunit;
+
+    // Main internal methods:
+    //
+    lbool         solve_                   (bool do_simp = true, bool turn_off_simp = false);
+    bool          asymm                    (Var v, CRef cr);
+    bool          asymmVar                 (Var v);
+    void          updateElimHeap           (Var v);
+    void          gatherTouchedClauses     ();
+    bool          merge                    (const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause);
+    bool          merge                    (const Clause& _ps, const Clause& _qs, Var v, int& size);
+    bool          backwardSubsumptionCheck (bool verbose = false);
+    bool          eliminateVar             (Var v);
+    void          extendModel              ();
+
+    void          removeClause             (CRef cr);
+    bool          strengthenClause         (CRef cr, Lit l);
+    bool          implied                  (const vec<Lit>& c);
+    void          relocAll                 (ClauseAllocator& to);
+};
+
+
+//=================================================================================================
+// Implementation of inline methods:
+
+
+inline bool SimpSolver::isEliminated (Var v) const { return eliminated[v]; }
+inline void SimpSolver::updateElimHeap(Var v) {
+    assert(use_simplification);
+    // if (!frozen[v] && !isEliminated(v) && value(v) == l_Undef)
+    if (elim_heap.inHeap(v) || (!frozen[v] && !isEliminated(v) && value(v) == l_Undef))
+        elim_heap.update(v); }
+
+
+inline bool SimpSolver::addClause    (const vec<Lit>& ps)    { ps.copyTo(add_tmp); return addClause_(add_tmp); }
+inline bool SimpSolver::addEmptyClause()                     { add_tmp.clear(); return addClause_(add_tmp); }
+inline bool SimpSolver::addClause    (Lit p)                 { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); }
+inline bool SimpSolver::addClause    (Lit p, Lit q)          { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); }
+inline bool SimpSolver::addClause    (Lit p, Lit q, Lit r)   { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); }
+inline void SimpSolver::setFrozen    (Var v, bool b) { frozen[v] = (char)b; if (use_simplification && !b) { updateElimHeap(v); } }
+
+inline bool SimpSolver::solve        (                     bool do_simp, bool turn_off_simp)  { budgetOff(); assumptions.clear(); return solve_(do_simp, turn_off_simp) == l_True; }
+inline bool SimpSolver::solve        (Lit p       ,        bool do_simp, bool turn_off_simp)  { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_(do_simp, turn_off_simp) == l_True; }
+inline bool SimpSolver::solve        (Lit p, Lit q,        bool do_simp, bool turn_off_simp)  { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_(do_simp, turn_off_simp) == l_True; }
+inline bool SimpSolver::solve        (Lit p, Lit q, Lit r, bool do_simp, bool turn_off_simp)  { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_(do_simp, turn_off_simp) == l_True; }
+inline bool SimpSolver::solve        (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){ 
+    budgetOff(); assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp) == l_True; }
+
+inline lbool SimpSolver::solveLimited (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){ 
+    assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp); }
+
+//=================================================================================================
+}
+
+#endif

+ 190 - 0
sources/simp/pmaple.py

@@ -0,0 +1,190 @@
+# -*- coding: utf-8 -*-
+# reasonLS
+# authors
+#
+# runs n instances of reasonLS in parallel (script code based on code of Norbert Manthey 2014)
+#
+
+# used libraries
+import os, signal, subprocess, time
+import sys, shutil, random, re 
+
+
+def check_pid(pid):        
+    """ Check For the existence of a unix pid. """
+    try:
+        os.kill(pid, 0)
+    except OSError:
+        return False
+    else:
+        return True
+
+#
+# usage and current PID
+#
+print ("c reasonLS SC18")
+print ("c authors")
+print ("c runs n instances of reasonLS in parallel")
+
+if (len(sys.argv) < 4):
+    print ("c usage: python pmapple.py <input.cnf> <seed> <numCores> [<proofFile>] [<tmpDirectory>]" ) #n is the number of instances to start
+    sys.exit(0)
+print ("c running with PID " + str(os.getpid()))
+
+#
+# Handle parameters
+#
+# get input file
+#
+inputFile = sys.argv[1]
+seed = int(sys.argv[2])
+numCores = int(sys.argv[3])
+if (numCores == 1):
+    print ("c does not make sense, please start reasonLS directly")
+    sys.exit(0)
+
+# set proof file
+if (len(sys.argv) > 4):
+    tmpProofz = sys.argv[4] 
+    path_proof = tmpProofz[tmpProofz.find('drup-file=')+10:]
+    pathz = os.path.dirname(path_proof)
+    proof = os.path.basename(path_proof)
+else:
+    proof = "/dev/null"
+
+#
+# setup tmp files
+#
+tmpDir = "/tmp/"
+print ("c found " + str(len(sys.argv)) + "parameters")
+if (len(sys.argv) > 5):
+    tmpDir = sys.argv[5]
+if (tmpDir[-1:] != '/'):
+    tmpDir = tmpDir + "/"
+
+#construction of temporary files for output
+
+# let user know that everything has been read correctly
+print ("c starting " + str(numCores) + " instances of reasonLS with seed " + str(
+    seed) + " on instance " + str(
+        inputFile) + " \nc writing temp files to  " + tmpDir)
+
+#
+# start the two solvers, each in its private process group
+#
+random.seed(seed)
+pids = set()
+pidsseed = set()
+seeds = set()
+
+confl = [0.9, 0.01, 1, 0.5, 0.6, 0.7, 0.8]
+area = [1.01, 1, 1.01, 1.05, 1.04, 1.03, 1.02]
+maxflip = [600, 600, 600, 600, 600, 600, 600]
+initflip = [100, 100, 100, 100, 100, 100, 100]
+raiseflip = [1.02, 1.02, 1.02, 1.02, 1.02, 1.02, 1.02]
+time = [0.35, 1.2, 0.35, 0.5, 0.45, 0.4, 0.35]
+
+tmpBassename = os.path.basename(inputFile)
+
+
+for i in range(0, numCores):
+    seed=random.randint(0,2147483647)
+    tmpFile = tmpDir + tmpBassename + "reasonLS_" + str(seed)
+    print ("c starting instance " + str(
+        i) + " of reasonLS started with seed " + str(seed))
+    print ("c writing to files " + tmpFile + ".out .err")
+    # start reasonLS
+    if (proof != "/dev/null"):
+        tmpProof = tmpDir + tmpBassename + proof + "reasonLS_" + str(seed)
+    else:
+        tmpProof = proof
+    reasonLSCallString = "./ReasonLS " + inputFile + " -drup-file=" + tmpProof  # add CNF file and tmp directory
+    reasonLSCallString = reasonLSCallString + " -conflRatio=" + str(confl[i % 7]) + " -areaRatio=" + str(area[i % 7])
+    reasonLSCallString = reasonLSCallString + " -maxFlipRatio=" + str(maxflip[i % 7]) + " -initFlipRatio=" + str(initflip[i % 7]) + " -raiseFlipRatio=" + str(raiseflip[i % 7])
+    reasonLSCallString = reasonLSCallString + " -timeRatio=" + str(time[i % 7]) + " -switchMode="
+    if (i < 7):
+        reasonLSCallString = reasonLSCallString + "2500"
+    else:
+        reasonLSCallString = reasonLSCallString + "0"
+
+    args = reasonLSCallString.split()
+    # split the actual command line
+    print ("c calling reasonLS with " + str(args))
+    reasonLSProcess = subprocess.Popen(
+        args,
+        stdout=open(tmpFile + ".out", "w"),
+        stderr=open(tmpFile + ".err", "w"),
+        preexec_fn=os.setpgrp)
+    pidsseed.add((reasonLSProcess.pid, seed))
+    pids.add(reasonLSProcess.pid)
+    seeds.add(seed)
+    print ("c started reasonLS instance with PID" + str(reasonLSProcess.pid))
+
+
+# wait until the first solver returns
+winner = ""
+winnerCode = 0
+while pids:
+    pid, retval = os.wait()
+    print ("c finished " + str(pid) + " with return value " + str(retval))
+    pids.remove(pid)
+    # extract the exit code
+    signal = retval & 255
+    exitCode = (retval >> 8) & 255
+    print ("c signal: " + str(signal) + " exit code: " + str(exitCode))
+    # if exit code is nice, select the winner
+    winnerseed = -1
+    if signal == 0 and (exitCode == 10 or exitCode == 20):
+        winnerCode = exitCode  # get exit code
+        for i in range(numCores):
+            proc = pidsseed.pop()
+            if proc[0] == pid:
+                winnerseed = proc[1]
+                break  # do not wait for the other process as well, if a solution has been found!
+    if winnerseed != -1:
+        break
+#
+# output the result
+#
+if winnerCode != 0:
+    print ("c winner seed: " + str(winnerseed))
+    tmpFile = tmpDir + tmpBassename + "reasonLS_" + str(winnerseed)
+    # for more recent python versions:
+    #	with open(tmpFile + ".out", "r") as f:
+
+    # for the competition 2014 version:
+    f = open(tmpFile + ".out", "r")
+    if f:
+        shutil.copyfileobj(f, sys.stdout)
+
+    if (proof != "/dev/null"):
+        tmpProof = proof + tmpBassename + "reasonLS_" + str(winnerseed)
+        if( not os.path.exists(pathz) ):
+            os.mkdir(pathz)
+        if( os.path.exists(tmpDir+tmpProof)):
+            os.system("mv " + tmpDir + tmpProof + " " + pathz + '/' +proof)
+    
+
+else:
+    print ("s UNKNOWN")
+
+# kill the other process, and its child processes
+for p in pids:
+    if(check_pid(p)):
+        os.kill(-p, 15)
+
+# clean up the temporary files
+for i in range(numCores):
+    seed = seeds.pop()
+    tmpFile = tmpDir + tmpBassename + "reasonLS_" + str(seed)
+    if(os.path.exists(tmpFile + ".err")):    
+        os.unlink(tmpFile + ".err")
+    if(os.path.exists(tmpFile + ".out")):
+        os.unlink(tmpFile + ".out")
+    if(proof != "/dev/null"):
+        tmpProof = tmpDir + tmpBassename + proof + "reasonLS_" + str(seed)
+        if(os.path.exists(tmpProof)):
+            os.unlink(tmpProof)
+
+# exit with the correct exit code
+sys.exit(winnerCode)

+ 4 - 0
sources/utils/Makefile

@@ -0,0 +1,4 @@
+EXEC      = system_test
+DEPDIR    = mtl
+
+include $(MROOT)/mtl/template.mk

+ 91 - 0
sources/utils/Options.cc

@@ -0,0 +1,91 @@
+/**************************************************************************************[Options.cc]
+Copyright (c) 2008-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#include "mtl/Sort.h"
+#include "utils/Options.h"
+#include "utils/ParseUtils.h"
+
+using namespace Minisat;
+
+void Minisat::parseOptions(int& argc, char** argv, bool strict)
+{
+    int i, j;
+    for (i = j = 1; i < argc; i++){
+        const char* str = argv[i];
+        if (match(str, "--") && match(str, Option::getHelpPrefixString()) && match(str, "help")){
+            if (*str == '\0')
+                printUsageAndExit(argc, argv);
+            else if (match(str, "-verb"))
+                printUsageAndExit(argc, argv, true);
+        } else {
+            bool parsed_ok = false;
+        
+            for (int k = 0; !parsed_ok && k < Option::getOptionList().size(); k++){
+                parsed_ok = Option::getOptionList()[k]->parse(argv[i]);
+
+                // fprintf(stderr, "checking %d: %s against flag <%s> (%s)\n", i, argv[i], Option::getOptionList()[k]->name, parsed_ok ? "ok" : "skip");
+            }
+
+            if (!parsed_ok)
+                if (strict && match(argv[i], "-"))
+                    fprintf(stderr, "ERROR! Unknown flag \"%s\". Use '--%shelp' for help.\n", argv[i], Option::getHelpPrefixString()), exit(1);
+                else
+                    argv[j++] = argv[i];
+        }
+    }
+
+    argc -= (i - j);
+}
+
+
+void Minisat::setUsageHelp      (const char* str){ Option::getUsageString() = str; }
+void Minisat::setHelpPrefixStr  (const char* str){ Option::getHelpPrefixString() = str; }
+void Minisat::printUsageAndExit (int argc, char** argv, bool verbose)
+{
+    const char* usage = Option::getUsageString();
+    if (usage != NULL)
+        fprintf(stderr, usage, argv[0]);
+
+    sort(Option::getOptionList(), Option::OptionLt());
+
+    const char* prev_cat  = NULL;
+    const char* prev_type = NULL;
+
+    for (int i = 0; i < Option::getOptionList().size(); i++){
+        const char* cat  = Option::getOptionList()[i]->category;
+        const char* type = Option::getOptionList()[i]->type_name;
+
+        if (cat != prev_cat)
+            fprintf(stderr, "\n%s OPTIONS:\n\n", cat);
+        else if (type != prev_type)
+            fprintf(stderr, "\n");
+
+        Option::getOptionList()[i]->help(verbose);
+
+        prev_cat  = Option::getOptionList()[i]->category;
+        prev_type = Option::getOptionList()[i]->type_name;
+    }
+
+    fprintf(stderr, "\nHELP OPTIONS:\n\n");
+    fprintf(stderr, "  --%shelp        Print help message.\n", Option::getHelpPrefixString());
+    fprintf(stderr, "  --%shelp-verb   Print verbose help message.\n", Option::getHelpPrefixString());
+    fprintf(stderr, "\n");
+    exit(0);
+}
+

+ 386 - 0
sources/utils/Options.h

@@ -0,0 +1,386 @@
+/***************************************************************************************[Options.h]
+Copyright (c) 2008-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_Options_h
+#define Minisat_Options_h
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+#include <string.h>
+
+#include "mtl/IntTypes.h"
+#include "mtl/Vec.h"
+#include "utils/ParseUtils.h"
+
+namespace Minisat {
+
+//==================================================================================================
+// Top-level option parse/help functions:
+
+
+extern void parseOptions     (int& argc, char** argv, bool strict = false);
+extern void printUsageAndExit(int  argc, char** argv, bool verbose = false);
+extern void setUsageHelp     (const char* str);
+extern void setHelpPrefixStr (const char* str);
+
+
+//==================================================================================================
+// Options is an abstract class that gives the interface for all types options:
+
+
+class Option
+{
+ protected:
+    const char* name;
+    const char* description;
+    const char* category;
+    const char* type_name;
+
+    static vec<Option*>& getOptionList () { static vec<Option*> options; return options; }
+    static const char*&  getUsageString() { static const char* usage_str; return usage_str; }
+    static const char*&  getHelpPrefixString() { static const char* help_prefix_str = ""; return help_prefix_str; }
+
+    struct OptionLt {
+        bool operator()(const Option* x, const Option* y) {
+            int test1 = strcmp(x->category, y->category);
+            return test1 < 0 || test1 == 0 && strcmp(x->type_name, y->type_name) < 0;
+        }
+    };
+
+    Option(const char* name_, 
+           const char* desc_,
+           const char* cate_,
+           const char* type_) : 
+      name       (name_)
+    , description(desc_)
+    , category   (cate_)
+    , type_name  (type_)
+    { 
+        getOptionList().push(this); 
+    }
+
+ public:
+    virtual ~Option() {}
+
+    virtual bool parse             (const char* str)      = 0;
+    virtual void help              (bool verbose = false) = 0;
+
+    friend  void parseOptions      (int& argc, char** argv, bool strict);
+    friend  void printUsageAndExit (int  argc, char** argv, bool verbose);
+    friend  void setUsageHelp      (const char* str);
+    friend  void setHelpPrefixStr  (const char* str);
+};
+
+
+//==================================================================================================
+// Range classes with specialization for floating types:
+
+
+struct IntRange {
+    int begin;
+    int end;
+    IntRange(int b, int e) : begin(b), end(e) {}
+};
+
+struct Int64Range {
+    int64_t begin;
+    int64_t end;
+    Int64Range(int64_t b, int64_t e) : begin(b), end(e) {}
+};
+
+struct DoubleRange {
+    double begin;
+    double end;
+    bool  begin_inclusive;
+    bool  end_inclusive;
+    DoubleRange(double b, bool binc, double e, bool einc) : begin(b), end(e), begin_inclusive(binc), end_inclusive(einc) {}
+};
+
+
+//==================================================================================================
+// Double options:
+
+
+class DoubleOption : public Option
+{
+ protected:
+    DoubleRange range;
+    double      value;
+
+ public:
+    DoubleOption(const char* c, const char* n, const char* d, double def = double(), DoubleRange r = DoubleRange(-HUGE_VAL, false, HUGE_VAL, false))
+        : Option(n, d, c, "<double>"), range(r), value(def) {
+        // FIXME: set LC_NUMERIC to "C" to make sure that strtof/strtod parses decimal point correctly.
+    }
+
+    operator      double   (void) const { return value; }
+    operator      double&  (void)       { return value; }
+    DoubleOption& operator=(double x)   { value = x; return *this; }
+
+    virtual bool parse(const char* str){
+        const char* span = str; 
+
+        if (!match(span, "-") || !match(span, name) || !match(span, "="))
+            return false;
+
+        char*  end;
+        double tmp = strtod(span, &end);
+
+        if (end == NULL) 
+            return false;
+        else if (tmp >= range.end && (!range.end_inclusive || tmp != range.end)){
+            fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name);
+            exit(1);
+        }else if (tmp <= range.begin && (!range.begin_inclusive || tmp != range.begin)){
+            fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name);
+            exit(1); }
+
+        value = tmp;
+        // fprintf(stderr, "READ VALUE: %g\n", value);
+
+        return true;
+    }
+
+    virtual void help (bool verbose = false){
+        fprintf(stderr, "  -%-12s = %-8s %c%4.2g .. %4.2g%c (default: %g)\n", 
+                name, type_name, 
+                range.begin_inclusive ? '[' : '(', 
+                range.begin,
+                range.end,
+                range.end_inclusive ? ']' : ')', 
+                value);
+        if (verbose){
+            fprintf(stderr, "\n        %s\n", description);
+            fprintf(stderr, "\n");
+        }
+    }
+};
+
+
+//==================================================================================================
+// Int options:
+
+
+class IntOption : public Option
+{
+ protected:
+    IntRange range;
+    int32_t  value;
+
+ public:
+    IntOption(const char* c, const char* n, const char* d, int32_t def = int32_t(), IntRange r = IntRange(INT32_MIN, INT32_MAX))
+        : Option(n, d, c, "<int32>"), range(r), value(def) {}
+ 
+    operator   int32_t   (void) const { return value; }
+    operator   int32_t&  (void)       { return value; }
+    IntOption& operator= (int32_t x)  { value = x; return *this; }
+
+    virtual bool parse(const char* str){
+        const char* span = str; 
+
+        if (!match(span, "-") || !match(span, name) || !match(span, "="))
+            return false;
+
+        char*   end;
+        int32_t tmp = strtol(span, &end, 10);
+
+        if (end == NULL) 
+            return false;
+        else if (tmp > range.end){
+            fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name);
+            exit(1);
+        }else if (tmp < range.begin){
+            fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name);
+            exit(1); }
+
+        value = tmp;
+
+        return true;
+    }
+
+    virtual void help (bool verbose = false){
+        fprintf(stderr, "  -%-12s = %-8s [", name, type_name);
+        if (range.begin == INT32_MIN)
+            fprintf(stderr, "imin");
+        else
+            fprintf(stderr, "%4d", range.begin);
+
+        fprintf(stderr, " .. ");
+        if (range.end == INT32_MAX)
+            fprintf(stderr, "imax");
+        else
+            fprintf(stderr, "%4d", range.end);
+
+        fprintf(stderr, "] (default: %d)\n", value);
+        if (verbose){
+            fprintf(stderr, "\n        %s\n", description);
+            fprintf(stderr, "\n");
+        }
+    }
+};
+
+
+// Leave this out for visual C++ until Microsoft implements C99 and gets support for strtoll.
+#ifndef _MSC_VER
+
+class Int64Option : public Option
+{
+ protected:
+    Int64Range range;
+    int64_t  value;
+
+ public:
+    Int64Option(const char* c, const char* n, const char* d, int64_t def = int64_t(), Int64Range r = Int64Range(INT64_MIN, INT64_MAX))
+        : Option(n, d, c, "<int64>"), range(r), value(def) {}
+ 
+    operator     int64_t   (void) const { return value; }
+    operator     int64_t&  (void)       { return value; }
+    Int64Option& operator= (int64_t x)  { value = x; return *this; }
+
+    virtual bool parse(const char* str){
+        const char* span = str; 
+
+        if (!match(span, "-") || !match(span, name) || !match(span, "="))
+            return false;
+
+        char*   end;
+        int64_t tmp = strtoll(span, &end, 10);
+
+        if (end == NULL) 
+            return false;
+        else if (tmp > range.end){
+            fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name);
+            exit(1);
+        }else if (tmp < range.begin){
+            fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name);
+            exit(1); }
+
+        value = tmp;
+
+        return true;
+    }
+
+    virtual void help (bool verbose = false){
+        fprintf(stderr, "  -%-12s = %-8s [", name, type_name);
+        if (range.begin == INT64_MIN)
+            fprintf(stderr, "imin");
+        else
+            fprintf(stderr, "%4"PRIi64, range.begin);
+
+        fprintf(stderr, " .. ");
+        if (range.end == INT64_MAX)
+            fprintf(stderr, "imax");
+        else
+            fprintf(stderr, "%4"PRIi64, range.end);
+
+        fprintf(stderr, "] (default: %"PRIi64")\n", value);
+        if (verbose){
+            fprintf(stderr, "\n        %s\n", description);
+            fprintf(stderr, "\n");
+        }
+    }
+};
+#endif
+
+//==================================================================================================
+// String option:
+
+
+class StringOption : public Option
+{
+    const char* value;
+ public:
+    StringOption(const char* c, const char* n, const char* d, const char* def = NULL) 
+        : Option(n, d, c, "<string>"), value(def) {}
+
+    operator      const char*  (void) const     { return value; }
+    operator      const char*& (void)           { return value; }
+    StringOption& operator=    (const char* x)  { value = x; return *this; }
+
+    virtual bool parse(const char* str){
+        const char* span = str; 
+
+        if (!match(span, "-") || !match(span, name) || !match(span, "="))
+            return false;
+
+        value = span;
+        return true;
+    }
+
+    virtual void help (bool verbose = false){
+        fprintf(stderr, "  -%-10s = %8s\n", name, type_name);
+        if (verbose){
+            fprintf(stderr, "\n        %s\n", description);
+            fprintf(stderr, "\n");
+        }
+    }    
+};
+
+
+//==================================================================================================
+// Bool option:
+
+
+class BoolOption : public Option
+{
+    bool value;
+
+ public:
+    BoolOption(const char* c, const char* n, const char* d, bool v) 
+        : Option(n, d, c, "<bool>"), value(v) {}
+
+    operator    bool     (void) const { return value; }
+    operator    bool&    (void)       { return value; }
+    BoolOption& operator=(bool b)     { value = b; return *this; }
+
+    virtual bool parse(const char* str){
+        const char* span = str; 
+        
+        if (match(span, "-")){
+            bool b = !match(span, "no-");
+
+            if (strcmp(span, name) == 0){
+                value = b;
+                return true; }
+        }
+
+        return false;
+    }
+
+    virtual void help (bool verbose = false){
+
+        fprintf(stderr, "  -%s, -no-%s", name, name);
+
+        for (uint32_t i = 0; i < 32 - strlen(name)*2; i++)
+            fprintf(stderr, " ");
+
+        fprintf(stderr, " ");
+        fprintf(stderr, "(default: %s)\n", value ? "on" : "off");
+        if (verbose){
+            fprintf(stderr, "\n        %s\n", description);
+            fprintf(stderr, "\n");
+        }
+    }
+};
+
+//=================================================================================================
+}
+
+#endif

+ 122 - 0
sources/utils/ParseUtils.h

@@ -0,0 +1,122 @@
+/************************************************************************************[ParseUtils.h]
+Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2007-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_ParseUtils_h
+#define Minisat_ParseUtils_h
+
+#include <stdlib.h>
+#include <stdio.h>
+
+#include <zlib.h>
+
+namespace Minisat {
+
+//-------------------------------------------------------------------------------------------------
+// A simple buffered character stream class:
+
+static const int buffer_size = 1048576;
+
+
+class StreamBuffer {
+    gzFile        in;
+    unsigned char buf[buffer_size];
+    int           pos;
+    int           size;
+
+    void assureLookahead() {
+        if (pos >= size) {
+            pos  = 0;
+            size = gzread(in, buf, sizeof(buf)); } }
+
+public:
+    explicit StreamBuffer(gzFile i) : in(i), pos(0), size(0) { assureLookahead(); }
+
+    int  operator *  () const { return (pos >= size) ? EOF : buf[pos]; }
+    void operator ++ ()       { pos++; assureLookahead(); }
+    int  position    () const { return pos; }
+};
+
+
+//-------------------------------------------------------------------------------------------------
+// End-of-file detection functions for StreamBuffer and char*:
+
+
+static inline bool isEof(StreamBuffer& in) { return *in == EOF;  }
+static inline bool isEof(const char*   in) { return *in == '\0'; }
+
+//-------------------------------------------------------------------------------------------------
+// Generic parse functions parametrized over the input-stream type.
+
+
+template<class B>
+static void skipWhitespace(B& in) {
+    while ((*in >= 9 && *in <= 13) || *in == 32)
+        ++in; }
+
+
+template<class B>
+static void skipLine(B& in) {
+    for (;;){
+        if (isEof(in)) return;
+        if (*in == '\n') { ++in; return; }
+        ++in; } }
+
+
+template<class B>
+static int parseInt(B& in) {
+    int     val = 0;
+    bool    neg = false;
+    skipWhitespace(in);
+    if      (*in == '-') neg = true, ++in;
+    else if (*in == '+') ++in;
+    if (*in < '0' || *in > '9') fprintf(stderr, "PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
+    while (*in >= '0' && *in <= '9')
+        val = val*10 + (*in - '0'),
+        ++in;
+    return neg ? -val : val; }
+
+
+// String matching: in case of a match the input iterator will be advanced the corresponding
+// number of characters.
+template<class B>
+static bool match(B& in, const char* str) {
+    int i;
+    for (i = 0; str[i] != '\0'; i++)
+        if (in[i] != str[i])
+            return false;
+
+    in += i;
+
+    return true; 
+}
+
+// String matching: consumes characters eagerly, but does not require random access iterator.
+template<class B>
+static bool eagerMatch(B& in, const char* str) {
+    for (; *str != '\0'; ++str, ++in)
+        if (*str != *in)
+            return false;
+    return true; }
+
+
+//=================================================================================================
+}
+
+#endif

+ 95 - 0
sources/utils/System.cc

@@ -0,0 +1,95 @@
+/***************************************************************************************[System.cc]
+Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2007-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#include "utils/System.h"
+
+#if defined(__linux__)
+
+#include <stdio.h>
+#include <stdlib.h>
+
+using namespace Minisat;
+
+// TODO: split the memory reading functions into two: one for reading high-watermark of RSS, and
+// one for reading the current virtual memory size.
+
+static inline int memReadStat(int field)
+{
+    char  name[256];
+    pid_t pid = getpid();
+    int   value;
+
+    sprintf(name, "/proc/%d/statm", pid);
+    FILE* in = fopen(name, "rb");
+    if (in == NULL) return 0;
+
+    for (; field >= 0; field--)
+        if (fscanf(in, "%d", &value) != 1)
+            printf("ERROR! Failed to parse memory statistics from \"/proc\".\n"), exit(1);
+    fclose(in);
+    return value;
+}
+
+
+static inline int memReadPeak(void)
+{
+    char  name[256];
+    pid_t pid = getpid();
+
+    sprintf(name, "/proc/%d/status", pid);
+    FILE* in = fopen(name, "rb");
+    if (in == NULL) return 0;
+
+    // Find the correct line, beginning with "VmPeak:":
+    int peak_kb = 0;
+    while (!feof(in) && fscanf(in, "VmPeak: %d kB", &peak_kb) != 1)
+        while (!feof(in) && fgetc(in) != '\n')
+            ;
+    fclose(in);
+
+    return peak_kb;
+}
+
+double Minisat::memUsed() { return (double)memReadStat(0) * (double)getpagesize() / (1024*1024); }
+double Minisat::memUsedPeak() { 
+    double peak = memReadPeak() / 1024;
+    return peak == 0 ? memUsed() : peak; }
+
+#elif defined(__FreeBSD__)
+
+double Minisat::memUsed(void) {
+    struct rusage ru;
+    getrusage(RUSAGE_SELF, &ru);
+    return (double)ru.ru_maxrss / 1024; }
+double MiniSat::memUsedPeak(void) { return memUsed(); }
+
+
+#elif defined(__APPLE__)
+#include <malloc/malloc.h>
+
+double Minisat::memUsed(void) {
+    malloc_statistics_t t;
+    malloc_zone_statistics(NULL, &t);
+    return (double)t.max_size_in_use / (1024*1024); }
+double Minisat::memUsedPeak(void) {return memUsed(); }
+#else
+double Minisat::memUsed() { 
+    return 0; }
+#endif

+ 60 - 0
sources/utils/System.h

@@ -0,0 +1,60 @@
+/****************************************************************************************[System.h]
+Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
+Copyright (c) 2007-2010, Niklas Sorensson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+associated documentation files (the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute,
+sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or
+substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
+OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+**************************************************************************************************/
+
+#ifndef Minisat_System_h
+#define Minisat_System_h
+
+#if defined(__linux__)
+#include <fpu_control.h>
+#endif
+
+#include "mtl/IntTypes.h"
+
+//-------------------------------------------------------------------------------------------------
+
+namespace Minisat {
+
+static inline double cpuTime(void); // CPU-time in seconds.
+extern double memUsed();            // Memory in mega bytes (returns 0 for unsupported architectures).
+extern double memUsedPeak();        // Peak-memory in mega bytes (returns 0 for unsupported architectures).
+
+}
+
+//-------------------------------------------------------------------------------------------------
+// Implementation of inline functions:
+
+#if defined(_MSC_VER) || defined(__MINGW32__)
+#include <time.h>
+
+static inline double Minisat::cpuTime(void) { return (double)clock() / CLOCKS_PER_SEC; }
+
+#else
+#include <sys/time.h>
+#include <sys/resource.h>
+#include <unistd.h>
+
+static inline double Minisat::cpuTime(void) {
+    struct rusage ru;
+    getrusage(RUSAGE_SELF, &ru);
+    return (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec / 1000000; }
+
+#endif
+
+#endif

+ 731 - 0
sources/utils/ccnr.cc

@@ -0,0 +1,731 @@
+
+#include "ccnr.h"
+//-------------------
+//in mersenne.cc
+const int M = 397;
+const unsigned int MATRIX_A = 0x9908b0dfUL;
+const unsigned int UPPER_MASK = 0x80000000UL;
+const unsigned int LOWER_MASK = 0x7fffffffUL;
+
+//---------------------------
+//functions in mersenne.h & mersenne.cpp
+
+/*
+  Notes on seeding
+
+  1. Seeding with an integer
+     To avoid different seeds mapping to the same sequence, follow one of
+     the following two conventions:
+     a) Only use seeds in 0..2^31-1     (preferred)
+     b) Only use seeds in -2^30..2^30-1 (2-complement machines only)
+
+  2. Seeding with an array (die-hard seed method)
+     The length of the array, len, can be arbitrarily high, but for lengths greater
+     than N, collisions are common. If the seed is of high quality, using more than
+     N values does not make sense.
+*/
+Mersenne::Mersenne() {
+  seed((int) std::time(0));
+}
+Mersenne::Mersenne(int s) {
+  seed(s);
+}
+Mersenne::Mersenne(unsigned int *init_key, int key_length) {
+  seed(init_key, key_length);
+}
+Mersenne::Mersenne(const Mersenne &copy) {
+  *this = copy;
+}
+Mersenne &Mersenne::operator=(const Mersenne &copy) {
+  for(int i = 0; i < N; i++)
+    mt[i] = copy.mt[i];
+  mti = copy.mti;
+  return *this;
+}
+void Mersenne::seed(int se) {
+  unsigned int s = ((unsigned int) (se << 1)) + 1;
+  // Seeds should not be zero. Other possible solutions (such as s |= 1)
+  // lead to more confusion, because often-used low seeds like 2 and 3 would
+  // be identical. This leads to collisions only for rarely used seeds (see
+  // note in header file).
+  mt[0] = s & 0xffffffffUL;
+  for(mti = 1; mti < N; mti++) {
+    mt[mti] = (1812433253UL * (mt[mti - 1] ^ (mt[mti - 1] >> 30)) + mti);
+    mt[mti] &= 0xffffffffUL;
+  }
+}
+void Mersenne::seed(unsigned int *init_key, int key_length) {
+  int i = 1, j = 0, k = (N > key_length ? N : key_length);
+  seed(19650218UL);
+  for(; k; k--) {
+    mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1664525UL)) + init_key[j] + j;
+    mt[i] &= 0xffffffffUL;
+    i++;
+    j++;
+    if(i >= N) {
+      mt[0] = mt[N-1];
+      i = 1;
+    }
+    if(j >= key_length)
+      j = 0;
+  }
+  for (k = N - 1; k; k--) {
+    mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1566083941UL)) - i;
+    mt[i] &= 0xffffffffUL;
+    i++;
+    if(i >= N) {
+      mt[0] = mt[N - 1];
+      i = 1;
+    }
+  }
+  mt[0] = 0x80000000UL;
+}
+unsigned int Mersenne::next32() {
+  unsigned int y;
+  static unsigned int mag01[2] = {0x0UL, MATRIX_A};
+  if(mti >= N) {
+    int kk;
+    for(kk = 0; kk < N - M; kk++) {
+      y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
+      mt[kk] = mt[kk + M] ^ (y >> 1) ^ mag01[y & 0x1UL];
+    }
+    for(; kk < N - 1; kk++) {
+      y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK);
+      mt[kk] = mt[kk + (M - N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
+    }
+    y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
+    mt[N - 1] = mt[M - 1] ^ (y >> 1) ^ mag01[y & 0x1UL];
+    mti = 0;
+  }
+  y = mt[mti++];
+  y ^= (y >> 11);
+  y ^= (y << 7) & 0x9d2c5680UL;
+  y ^= (y << 15) & 0xefc60000UL;
+  y ^= (y >> 18);
+  return y;
+}
+int Mersenne::next31() {
+  return (int) (next32() >> 1);
+}
+double Mersenne::nextClosed() { 
+  unsigned int a = next32() >> 5, b = next32() >> 6;
+  return (a * 67108864.0 + b) * (1.0/9007199254740991.0); 
+} 
+double Mersenne::nextHalfOpen() { 
+  unsigned int a = next32() >> 5, b = next32() >> 6;
+  return (a * 67108864.0 + b) * (1.0/9007199254740992.0); 
+}
+double Mersenne::nextOpen() { 
+  unsigned int a = next32() >> 5, b = next32() >> 6;
+  return (0.5 + a * 67108864.0 + b) * (1.0/9007199254740991.0); 
+} 
+int Mersenne::next(int bound) {
+  unsigned int value;
+  do {
+    value = next31();
+  } while(value + (unsigned int) bound >= 0x80000000UL);
+  // Just using modulo doesn't lead to uniform distribution. This does.
+  return (int) (value % bound);
+}
+//functions in ls.cpp & ls.h
+//-----------------------
+//constructor with default setting.
+ls_solver::ls_solver()
+{
+	_additional_len = 10;
+	_max_tries = 1;//100
+	_max_steps = 20000000;	//2 0000 0000
+	_random_seed = 1;
+	_time_limit = 3000;		
+	_swt_threshold = 50;
+	_swt_p = 0.3;
+	_swt_q = 0.7;
+}
+/******************************the top function******************************/
+/**********************************build instance*******************************/
+bool ls_solver::make_space() 
+{
+	if(0==_num_vars || 0==_num_clauses) {cout<<"The formula size is zero. You may forgot to read the formula."<<endl; return false;}	
+	// _vars.reserve(_num_vars+_additional_len);
+	// _clauses.reserve(_num_clauses+_additional_len);
+	// _solution.reserve(_num_vars+_additional_len);	
+	// _index_in_unsat_clauses.reserve(_num_clauses+_additional_len);
+	// _index_in_unsat_vars.reserve(_num_vars+_additional_len);	
+	_vars.resize(_num_vars+_additional_len);
+	_clauses.resize(_num_clauses+_additional_len);
+	_solution.resize(_num_vars+_additional_len);	
+	_index_in_unsat_clauses.resize(_num_clauses+_additional_len);
+	_index_in_unsat_vars.resize(_num_vars+_additional_len);	
+	
+	return true;
+}
+void ls_solver::build_neighborhood()
+{
+	int	i, j, count;
+	int v, c;
+	vector<bool> neighbor_flag(_num_vars+_additional_len);
+	for (j=0; j<neighbor_flag.size(); ++j ) {neighbor_flag[j] = 0;}
+	for (v=1; v <= _num_vars; ++v)
+	{
+		variable * vp = &(_vars[v]);
+		//vector<lit>& vp2=_vars[v].literals;
+		for (lit lv : vp->literals)
+		{
+			c = lv.clause_num;
+			for (lit lc : _clauses[c].literals)
+			{
+				if (!neighbor_flag[lc.var_num] && lc.var_num!=v)
+				{
+					neighbor_flag[lc.var_num] = 1;
+					vp->neighbor_var_nums.push_back(lc.var_num);
+				}
+			}
+		}
+		for (j=0; j<vp->neighbor_var_nums.size(); ++j) {neighbor_flag[vp->neighbor_var_nums[j]] = 0;}
+	}
+}
+bool ls_solver::build_instance(string inst)
+{
+	string line;
+	istringstream iss;
+	int c, v, i;
+	int cur_lit;
+	bool lit_redundent, clause_tautology;
+	string tempstr1, tempstr2;	
+	vector<int> temp_clause;	
+	ifstream fin(inst.c_str());
+	if(!fin.is_open()) return false;	
+	while(getline(fin, line))
+	{
+		if(line.substr(0, 1) == "c") continue;
+		else if(line.substr(0, 1) == "p")
+		{
+			//reassign_istringstream(iss, line);
+			iss.clear();
+			iss.str(line);
+			iss.seekg(0, ios::beg);	
+			iss >> tempstr1 >> tempstr2 >> _num_vars >> _num_clauses;
+			break;
+		}
+	}	
+	if(!make_space()) return false;
+	//read clauses, each at a time
+	for(c=0; c < _num_clauses; )
+	{
+		clause_tautology = false;
+		temp_clause.clear();
+		vector<int>().swap(temp_clause);		
+		fin>>cur_lit;
+		while(cur_lit!=0) 
+		{
+			if(!clause_tautology)
+			{
+				lit_redundent = false;
+				for(int item : temp_clause)
+				{
+					if(cur_lit == item) {lit_redundent = true; break;}
+					else if(cur_lit == -item) {clause_tautology = true; break;}
+				}			
+				if(!lit_redundent)
+				{
+					temp_clause.push_back(cur_lit);
+				}
+			}
+			fin>>cur_lit;
+		}		
+		if(!clause_tautology)
+		{
+			for(int item : temp_clause)
+			{
+				_clauses[c].literals.push_back( lit(item,c) );
+			}			
+			c++;
+		}
+		else
+		{
+			_num_clauses--;
+			temp_clause.clear();
+			vector<int>().swap(temp_clause);
+		}		
+	}	
+	fin.close();
+	/********finish reading the input file****************/	
+	//build variables data structure
+	for (c=0; c < _num_clauses; c++) 
+	{
+		for(lit item: _clauses[c].literals)
+		{
+			v = item.var_num;
+			_vars[v].literals.push_back(item);
+		}
+	}	
+	build_neighborhood();
+	return true;
+}
+/****************local search**********************************/
+//bool  *return value modified
+bool 	ls_solver::local_search( const vector<bool>* init_solution)
+{
+	bool result = false;
+	int	flipv;	
+	_random_gen.seed(_random_seed);	
+	_best_found_cost = _num_clauses;
+	_best_cost_time = 0;
+	for(int t=0; t < _max_tries; t++)
+	{
+		initialize(init_solution);
+		if (0 == _unsat_clauses.size()) {result = true;break;}	//1
+		for (_step=0; _step < _max_steps; _step++)
+		{
+			flipv = pick_var();
+			flip(flipv);	
+			if (_unsat_clauses.size() < _best_found_cost) {_best_found_cost = _unsat_clauses.size(); _best_cost_time = get_runtime();}
+			if (0 == _unsat_clauses.size()) {result = true;break;} //1
+			if (get_runtime() > _time_limit) {result = false;break;} //0
+		}
+		if (0 == _unsat_clauses.size()) {result = true;break;}//1
+		if (get_runtime() > _time_limit) {result = false;break;}//0
+	}
+	return result;
+}
+/**********************************initialize*******************************/
+void	ls_solver::clear_prev_data()
+{
+	_unsat_clauses.clear();
+	vector<int>().swap(_unsat_clauses);	
+	_ccd_vars.clear();
+	vector<int>().swap(_ccd_vars);	
+	_unsat_vars.clear();
+	vector<int>().swap(_unsat_vars);	
+	for (int &item : _index_in_unsat_clauses) item = 0;	
+	for (int &item : _index_in_unsat_vars) item = 0;
+}
+void	ls_solver::initialize(const vector<bool>* init_solution)
+{
+	int v, c;
+	clear_prev_data();	
+	if (!init_solution)
+	{
+		//default random generation
+		//cout<<"c using random initial solution"<<endl;
+		for(v=1; v <= _num_vars; v++)
+		{
+			_solution[v] = (_random_gen.next(2)==0 ? 0 :1);
+		}
+	}
+	else
+	{
+		//cout<<"ok\n";
+		if (init_solution->size()!=_num_vars) {cout<<"c Error: the init solution's size is not equal to the number of variables."<<endl; exit(0);}		
+		for(v=1; v <= _num_vars; v++)
+		{
+			_solution[v] = init_solution->at(v-1);
+		}
+		//cout<<"ok1\n";
+	}
+	//unsat_appears, will be updated when calling unsat_a_clause function.
+	for(v=1; v <= _num_vars; v++) { _vars[v].unsat_appear = 0;}	
+	//initialize data structure of clauses according to init solution
+	for(c=0; c < _num_clauses; c++)
+	{
+		_clauses[c].sat_count = 0;
+		_clauses[c].sat_var = -1;
+		_clauses[c].weight = 1;
+		
+		for (lit l : _clauses[c].literals)
+		{
+			if ( _solution[l.var_num] == l.sense)
+			{
+				_clauses[c].sat_count++;
+				_clauses[c].sat_var = l.var_num;
+			}
+		}		
+		if (0 == _clauses[c].sat_count) {unsat_a_clause(c);}
+	}
+	_avg_clause_weight = 1;
+	_delta_total_clause_weight = 0;	
+	initialize_variable_datas();
+}
+void	ls_solver::initialize_variable_datas()
+{
+	int v, c, i;
+	variable * vp;	
+	//scores
+	for(v=1; v <= _num_vars; v++)
+	{
+		vp = &(_vars[v]);
+		vp->score = 0;
+		for( lit l : vp->literals)
+		{
+			c = l.clause_num;
+			if(0 == _clauses[c].sat_count) {vp->score += _clauses[c].weight;}
+			else if(1 == _clauses[c].sat_count && l.sense == _solution[l.var_num]) {vp->score -= _clauses[c].weight;}
+		}
+	}	
+	//last flip step
+	for(v=1; v <= _num_vars; v++) { _vars[v].last_flip_step = 0;}	
+	//cc datas
+	for(v=1; v <= _num_vars; v++) 
+	{ 
+		vp = &(_vars[v]);		
+		vp->cc_value = 1;
+		if (vp->score>0) //&&_vars[v].cc_value==1
+		{
+			_ccd_vars.push_back(v);
+			vp->is_in_ccd_vars = 1;
+		}
+		else {vp->is_in_ccd_vars = 0;}
+	}	
+	//the virtual var 0
+	vp = &(_vars[0]);
+	vp->score = vp->cc_value = vp->is_in_ccd_vars = vp->last_flip_step = 0;
+}
+/*********************end initialize functions*********************************/
+/**********************pick variable*******************************************/
+int 	ls_solver::pick_var()
+{
+	int         i,k,c,v;
+	int         best_var=0, best_score;
+	lit*		clause_c;	
+	if (_ccd_vars.size()>0)
+	{
+		best_var = _ccd_vars[0];
+		for (int v : _ccd_vars)
+		{
+			if (_vars[v].score > _vars[best_var].score) {best_var = v;}
+			else if(_vars[v].score == _vars[best_var].score && _vars[v].last_flip_step < _vars[best_var].last_flip_step) {best_var = v;}
+		}		
+		return best_var;
+	}
+	
+	//Aspriation Mode
+	_aspiration_score=_avg_clause_weight;
+	for(i=0;i<_unsat_vars.size();++i)
+	{
+		v=_unsat_vars[i];
+		if(_vars[v].score>_aspiration_score)
+		{
+			best_var=v;
+			break;
+		}
+	}
+	for(++i;i<_unsat_vars.size();++i)
+	{
+		v=_unsat_vars[i];
+		if(_vars[v].score>_vars[best_var].score) best_var=v;
+		else if(_vars[v].score==_vars[best_var].score && _vars[v].last_flip_step<_vars[best_var].last_flip_step) best_var=v;
+	}
+	if(best_var!=0) return best_var;
+	
+	/**Diversification Mode**/
+	update_clause_weights();	
+	/*focused random walk*/	
+	c = _unsat_clauses[_random_gen.next(_unsat_clauses.size())];
+	clause * cp = &(_clauses[c]);	
+	best_var = cp->literals[0].var_num;
+	for (k=1; k < cp->literals.size(); k++)
+	{
+		v = cp->literals[k].var_num;
+		if (_vars[v].score > _vars[best_var].score) {best_var = v;}
+		else if(_vars[v].score == _vars[best_var].score && _vars[v].last_flip_step < _vars[best_var].last_flip_step) {best_var = v;}
+	}	
+	return best_var;
+}
+/************************flip and update functions*****************************/
+void	ls_solver::flip(int flipv)
+{
+	int c, v;
+	lit* clause_c;
+	lit* p;
+	lit* q;	
+	_solution[flipv] = 1-_solution[flipv];
+	int org_flipv_score = _vars[flipv].score;	
+	for (lit l : _vars[flipv].literals)
+	{
+		clause * cp = &(_clauses[l.clause_num]);		
+		if (_solution[flipv] == l.sense)
+		{
+			cp->sat_count++;
+			if (1 == cp->sat_count) 
+			{ 
+				sat_a_clause(l.clause_num);				
+				cp->sat_var = flipv; 
+				for (lit lc : cp->literals) {_vars[lc.var_num].score -= cp->weight;}
+			}
+			else if (2 == cp->sat_count) {_vars[cp->sat_var].score += cp->weight;}
+		}
+		else
+		{
+			cp->sat_count--;
+			if (0 == cp->sat_count) 
+			{
+				unsat_a_clause(l.clause_num);				
+				for (lit lc : cp->literals) {_vars[lc.var_num].score += cp->weight;}
+			}
+			else if (1 == cp->sat_count) 
+			{
+				for (lit lc : cp->literals)
+				{
+					if (_solution[lc.var_num]==lc.sense) 
+					{
+						_vars[lc.var_num].score-= cp->weight; 
+						cp->sat_var = lc.var_num; 
+						break;
+					}
+				}
+			}
+		}
+	}
+	_vars[flipv].score = -org_flipv_score;
+	_vars[flipv].last_flip_step = _step;	
+	//update cc_values
+	update_cc_after_flip(flipv);
+}
+void	ls_solver::update_cc_after_flip(int flipv)
+{
+	int index, v, last_item;	
+	variable * vp = &(_vars[flipv]);	
+	vp->cc_value = 0;	
+	for (index=_ccd_vars.size()-1; index>=0; index--)
+	{
+		v = _ccd_vars[index];
+		if (_vars[v].score<=0)
+		{
+			last_item = _ccd_vars.back();
+			_ccd_vars.pop_back();
+			_ccd_vars[index]=last_item;
+			_vars[v].is_in_ccd_vars = 0;
+		}
+	}	
+	//update all flipv's neighbor's cc to be 1
+	for (int v : vp->neighbor_var_nums)
+	{
+		_vars[v].cc_value = 1;		
+		if (_vars[v].score>0 && !(_vars[v].is_in_ccd_vars))
+		{
+			_ccd_vars.push_back(v);
+			_vars[v].is_in_ccd_vars = 1;
+		}
+	}	
+}
+/**********************end flip and update functions***************************/
+/*********************functions for basic operations***************************/
+void 	ls_solver::sat_a_clause(int the_clause)
+{
+	int index,last_item;
+	//use the position of the clause to store the last unsat clause in stack
+	last_item = _unsat_clauses.back();
+	_unsat_clauses.pop_back();
+	index = _index_in_unsat_clauses[the_clause];
+	_unsat_clauses[index] = last_item;
+	_index_in_unsat_clauses[last_item] = index;
+	//update unsat_appear and unsat_vars
+	for (lit l : _clauses[the_clause].literals)
+	{
+		_vars[l.var_num].unsat_appear--;
+		if (0 == _vars[l.var_num].unsat_appear)
+		{
+			last_item = _unsat_vars.back();
+			_unsat_vars.pop_back();			
+			index = _index_in_unsat_vars[l.var_num];
+			_unsat_vars[index] = last_item;
+			_index_in_unsat_vars[last_item] = index;
+		}
+	}
+}
+void ls_solver::unsat_a_clause(int the_clause)
+{
+	_index_in_unsat_clauses[the_clause] = _unsat_clauses.size();
+	_unsat_clauses.push_back(the_clause);	
+	//update unsat_appear and unsat_vars
+	for (lit l : _clauses[the_clause].literals)
+	{
+		_vars[l.var_num].unsat_appear++;
+		if (1 == _vars[l.var_num].unsat_appear)
+		{
+			_index_in_unsat_vars[l.var_num] = _unsat_vars.size();
+			_unsat_vars.push_back(l.var_num);
+		}
+	}
+}
+/************************clause weighting********************************/
+void ls_solver::update_clause_weights()
+{
+	for (int c : _unsat_clauses) {_clauses[c].weight++;}
+	for (int v : _unsat_vars)
+	{
+		_vars[v].score += _vars[v].unsat_appear;
+		if (_vars[v].score>0 && 1==_vars[v].cc_value && !(_vars[v].is_in_ccd_vars))
+		{
+			_ccd_vars.push_back(v);
+			_vars[v].is_in_ccd_vars = 1;
+		}
+	}
+	_delta_total_clause_weight += _unsat_clauses.size();
+	if (_delta_total_clause_weight >= _num_clauses)
+	{
+		_avg_clause_weight += 1;
+		_delta_total_clause_weight -= _num_clauses;	
+		if (_avg_clause_weight > _swt_threshold) {smooth_clause_weights();}
+	}
+}
+void	ls_solver::smooth_clause_weights()
+{
+	int v,c;
+	for(v=1; v <= _num_vars; v++) { _vars[v].score=0;}
+	int	scale_avg = _avg_clause_weight * _swt_q;
+	_avg_clause_weight = 0;
+	_delta_total_clause_weight=0;
+	clause * cp;
+	for (c=0; c < _num_clauses; ++c)
+	{
+		cp = &(_clauses[c]);
+		cp->weight = cp->weight * _swt_p + scale_avg;
+		if (cp->weight<1) cp->weight=1;
+		_delta_total_clause_weight += cp->weight;
+		if (_delta_total_clause_weight >= _num_clauses)
+		{
+			_avg_clause_weight += 1;
+			_delta_total_clause_weight -= _num_clauses;
+		}
+		if (0==cp->sat_count)
+		{
+			for (lit l : cp->literals) {_vars[l.var_num].score += cp->weight;}
+		}
+		else if (1==cp->sat_count) {_vars[cp->sat_var].score -= cp->weight;}
+		
+	}
+	//reset ccd_vars
+	_ccd_vars.clear();
+	vector<int>().swap(_ccd_vars);
+	variable * vp;
+	for(v=1; v <= _num_vars; v++)
+	{
+		vp = &(_vars[v]);
+		if (vp->score>0 && 1==vp->cc_value)
+		{
+			_ccd_vars.push_back(v);
+			vp->is_in_ccd_vars = 1;
+		}
+		else {vp->is_in_ccd_vars = 0;}
+	}
+}
+/***parse parameters*****************/
+bool 	ls_solver::parse_arguments(int argc, char ** argv)
+{	
+	bool flag_inst = false;
+	for (int i=1; i<argc; i++)
+	{
+		if(strcmp(argv[i],"-inst")==0)
+		{
+			i++;
+			if(i>=argc) return false;
+			_inst_file = argv[i];
+			flag_inst = true;
+			continue;
+		}
+		else if(strcmp(argv[i],"-seed")==0)
+		{
+			i++;
+			if(i>=argc) return false;
+			sscanf(argv[i], "%d", &_random_seed);
+			continue;
+		}
+	}
+	if (flag_inst) return true;
+	else return false;
+}
+/*****print solutions*****************/
+void 	ls_solver::print_solution(bool need_verify)
+{
+	if (0==get_cost()) cout<<"s SATISFIABLE"<<endl;
+	else cout<<"s UNKNOWN"<<endl;
+	bool sat_flag = false;
+	if (need_verify)
+	{
+		for (int c=0; c < _num_clauses; c++)
+		{
+			sat_flag = false;
+			for (lit l : _clauses[c].literals)
+			{
+				if (_solution[l.var_num] == l.sense) {sat_flag = true; break; }
+			}
+			if (!sat_flag) {cout<<"c Error: verify error in clause "<<c<<endl; return;}
+		}
+		cout<<"c Verified."<<endl;
+	}
+	cout<<"v";
+	for (int v=1; v <= _num_vars; v++)
+	{
+		cout<<' ';
+		if (_solution[v]==0) cout<<'-';
+		cout<<v;
+	}
+	cout<<endl;
+}
+
+
+void	ls_solver::simple_print()
+{
+	cout<<'\t'<<_best_found_cost<<'\t'<<_best_cost_time<<endl;
+}
+//=========================
+
+
+// bool callUnCom(string inst){
+// 	class ls_solver ccnr;
+
+// 	start_timing();
+	
+// 	//string inst = argv[1];
+// 	int	ret = ccnr.build_instance(inst);
+// 	if (!ret) { cout << "Invalid filename: " << inst << endl; return 1;}
+
+// 	vector<bool> * vp = 0;  //can set initial solution vector here.
+	
+// 	cout<<inst;
+// 	//初始解在这里处理
+// 	if(ccnr.local_search(vp)){
+// 		ccnr.print_solution();
+// 	}else{
+// 		cout<<"unknown\n";
+// 	}
+	
+	
+// 	return 0;
+// }
+
+
+/*
+//main function
+			
+int main(int argc, char* argv[]) {
+
+	ls_solver ccnr;
+
+	start_timing();
+	
+	string inst = argv[1];
+	int	ret = ccnr.build_instance(inst);
+	if (!ret) { cout << "Invalid filename: " << argv[1] << endl; return 1;}
+
+	vector<bool> * vp = 0;  //can set initial solution vector here.
+	
+	cout<<inst;
+	//初始解在这里处理
+	if(ccnr.local_search(vp)){
+		ccnr.print_solution();
+	}else{
+		cout<<"unknown\n";
+	}
+	
+	//bool need_verify = true;
+	//ccnr.print_solution(need_verify);
+	
+	
+	return 0;
+}
+//=========================
+*/
+
+

+ 164 - 0
sources/utils/ccnr.h

@@ -0,0 +1,164 @@
+#ifndef CCNR_H
+#define CCNR_H
+
+//heads
+#include <vector>
+#include <iostream>
+#include <fstream>
+#include <sstream>
+#include <cmath>
+#include <cstdlib>
+#include <string.h>
+#include <stdio.h>
+#include <ctime>
+#include <vector>
+//these two h files are for timing under linux
+#include <sys/times.h> 
+#include <unistd.h>
+//---------------------
+using namespace std;
+
+
+//--------------------------
+//functions in basis.h & basis.cpp
+struct lit {
+	unsigned char sense:1;	//is 1 for true literals, 0 for false literals.
+	int clause_num:31;		//clause num, begin with 0
+	int var_num;			//variable num, begin with 1
+	lit(int the_lit, int the_clause) {
+		var_num = abs(the_lit);
+		clause_num = the_clause;
+		sense = the_lit>0 ? 1: 0;
+		}
+	struct lit& operator^=(const struct lit &l) {
+		sense ^= l.sense;
+		clause_num ^= l.clause_num;
+		var_num ^= l.var_num;
+		return *this;
+	}
+	void reset(void) {
+		sense = 0;
+		clause_num = 0;
+		var_num = 0;
+	}
+	bool operator==(const struct lit &l) const {
+		return sense == l.sense && clause_num == l.clause_num && var_num == l.var_num;
+	}
+	bool operator!=(const struct lit &l) const {
+		return !(*this == l);
+	}
+};
+struct variable {
+	vector<lit> literals;
+	vector<int>	neighbor_var_nums;	
+	long long	score;
+	long long	last_flip_step;
+	int			unsat_appear;	
+	bool		cc_value;
+	bool		is_in_ccd_vars;
+};
+struct clause {
+	vector<lit> 	literals;	
+	int		sat_count;
+	int		sat_var;	
+	long long	weight;
+};
+//timing
+static struct tms _start_time;	
+static double get_runtime() {
+	struct tms stop;
+	times(&stop);
+	return (double) (stop.tms_utime - _start_time.tms_utime +stop.tms_stime - _start_time.tms_stime) / sysconf(_SC_CLK_TCK);
+}
+static void  start_timing() { times(&_start_time);}
+//;;;;;;;
+
+
+//---------------------------
+//functions in mersenne.h & mersenne.cpp
+
+class Mersenne {
+  static const int N = 624;
+  unsigned int mt[N];
+  int mti;
+public:
+  Mersenne();             // seed with time-dependent value
+  Mersenne(int seed);     // seed with int value; see comments for the seed() method
+  Mersenne(unsigned int *array, int count); // seed with array
+  Mersenne(const Mersenne &copy);
+  Mersenne &operator=(const Mersenne &copy);
+  void seed(int s);
+  void seed(unsigned int *array, int len);
+  unsigned int next32();  // generates random integer in [0..2^32-1]
+  int next31();           // generates random integer in [0..2^31-1]
+  double nextClosed();    // generates random float in [0..1], 2^53 possible values
+  double nextHalfOpen();  // generates random float in [0..1), 2^53 possible values
+  double nextOpen();      // generates random float in (0..1), 2^53 possible values
+  int next(int bound);    // generates random integer in [0..bound), bound < 2^31
+};
+
+class ls_solver {
+public:
+	ls_solver();
+	bool 	parse_arguments(int argc, char ** argv);
+	bool	build_instance(string inst);
+	bool	local_search( const vector<bool>* init_solution = 0);	
+	void 	print_solution(bool need_verify=0);
+	void	simple_print();
+	int		get_best_cost() {return _best_found_cost;}	
+	void	run(int argc, char ** argv);	
+//private:
+	//formula
+	string				_inst_file;
+	vector<variable> 	_vars;
+	vector<clause>  	_clauses;
+	int		_num_vars;
+	int		_num_clauses;
+	int		_additional_len;
+	//data structure used
+	vector<int>		_unsat_clauses;
+	vector<int>		_index_in_unsat_clauses;
+	vector<int>		_unsat_vars;
+	vector<int>		_index_in_unsat_vars;
+	vector<int>		_ccd_vars;
+	//solution information
+	vector<bool> 	_solution;
+	int		_best_found_cost;
+	double	_best_cost_time;
+	long long 	_step;
+	long long	_max_steps;
+	int			_max_tries;
+	int			_time_limit;
+	//aiding data structure
+	Mersenne		_random_gen;		//random generator
+	int				_random_seed;
+	//algorithmic parameters
+	///////////////////////////
+	bool 	_aspiration_active;
+	int 	_aspiration_score;
+	//clause weighting
+	int   	_swt_threshold;
+	float 	_swt_p;//w=w*p+ave_w*q
+	float 	_swt_q;
+	int		_avg_clause_weight;
+	long long		_delta_total_clause_weight;
+	//main functions
+	void	initialize(const vector<bool>* init_solution = 0);
+	void	initialize_variable_datas();
+	void	clear_prev_data();
+	int		pick_var();
+	void	flip(int flipv);
+	void	update_cc_after_flip(int flipv);
+	void 	update_clause_weights();
+	void	smooth_clause_weights();
+	//funcitons for basic operations
+	void	sat_a_clause(int the_clause);
+	void	unsat_a_clause(int the_clause);
+	//functions for buiding data structure
+	bool	make_space();
+	void	build_neighborhood();
+	int		get_cost() {return _unsat_clauses.size();}
+		
+};
+
+#endif