#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>

using namespace std;

struct Formula {
    int nvars = 0;
    vector<vector<int>> clauses;
};

struct Timer {
    chrono::steady_clock::time_point start = chrono::steady_clock::now();
    double elapsed() const {
        return chrono::duration<double>(chrono::steady_clock::now() - start).count();
    }
};

struct XorShift64 {
    uint64_t x;
    explicit XorShift64(uint64_t seed) : x(seed ? seed : 1) {}
    uint64_t next() {
        x ^= x >> 12;
        x ^= x << 25;
        x ^= x >> 27;
        return x * 2685821657736338717ULL;
    }
    int randint(int n) { return int(next() % uint64_t(n)); }
    double unit() { return double(next() >> 11) * (1.0 / 9007199254740992.0); }
};

static bool parse_dimacs(const string& path, Formula& f) {
    ifstream in(path);
    if (!in) return false;
    string tok;
    int declared_clauses = 0;
    while (in >> tok) {
        if (tok == "c") {
            string rest;
            getline(in, rest);
        } else if (tok == "p") {
            string cnf;
            in >> cnf >> f.nvars >> declared_clauses;
            if (cnf != "cnf" || f.nvars <= 0 || declared_clauses < 0) return false;
            f.clauses.reserve(declared_clauses);
        } else {
            int lit = stoi(tok);
            vector<int> c;
            while (lit != 0) {
                if (abs(lit) > f.nvars) return false;
                c.push_back(lit);
                if (!(in >> lit)) return false;
            }
            f.clauses.push_back(std::move(c));
        }
    }
    return f.nvars > 0;
}

static bool verify_model(const Formula& f, const vector<unsigned char>& val) {
    if ((int)val.size() != f.nvars + 1) return false;
    for (const auto& c : f.clauses) {
        bool sat = false;
        for (int lit : c) {
            int v = abs(lit);
            if ((lit > 0 && val[v]) || (lit < 0 && !val[v])) {
                sat = true;
                break;
            }
        }
        if (!sat) return false;
    }
    return true;
}

static void print_model(const Formula& f, const vector<unsigned char>& val) {
    cout << "s SATISFIABLE\n";
    cout << "v";
    for (int v = 1; v <= f.nvars; ++v) cout << ' ' << (val[v] ? v : -v);
    cout << " 0\n";
}

static bool stochastic_3sat_search(const Formula& f, double limit, vector<unsigned char>& out) {
    bool all3 = true;
    for (const auto& c : f.clauses) all3 &= (c.size() == 3);
    if (!all3 || f.nvars <= 0 || f.clauses.empty()) return false;

    const int n = f.nvars;
    const int m = (int)f.clauses.size();
    vector<array<int, 3>> cls(m);
    vector<vector<int>> occ(n + 1);
    for (int i = 0; i < m; ++i) {
        for (int k = 0; k < 3; ++k) {
            cls[i][k] = f.clauses[i][k];
            occ[abs(cls[i][k])].push_back(i);
        }
    }

    Timer timer;
    const double cb_values[] = {2.30, 2.06, 2.85, 1.70};
    long long total_flips = 0;
    int global_best_unsat = m + 1;
    for (int seed = 1; timer.elapsed() < limit; ++seed) {
        XorShift64 rng(0x9e3779b97f4a7c15ULL * uint64_t(seed) + 0x123456789abcdefULL);
        double cb = cb_values[seed % 4];
        vector<unsigned char> val(n + 1);
        for (int v = 1; v <= n; ++v) val[v] = rng.next() & 1U;

        vector<unsigned char> satcnt(m, 0);
        vector<int> unsat;
        vector<int> pos(m, -1);
        unsat.reserve(m);
        for (int i = 0; i < m; ++i) {
            int cnt = 0;
            for (int lit : cls[i]) cnt += (val[abs(lit)] == (lit > 0));
            satcnt[i] = (unsigned char)cnt;
            if (cnt == 0) {
                pos[i] = (int)unsat.size();
                unsat.push_back(i);
            }
        }
        if ((int)unsat.size() < global_best_unsat) {
            global_best_unsat = (int)unsat.size();
            out = val;
        }

        while (timer.elapsed() < limit) {
            if (unsat.empty()) {
                out = std::move(val);
                cerr << "c sls solved seed=" << seed << " flips=" << total_flips << "\n";
                return verify_model(f, out);
            }
            if ((int)unsat.size() < global_best_unsat) {
                global_best_unsat = (int)unsat.size();
                out = val;
            }
            int ci = unsat[rng.randint((int)unsat.size())];
            double weights[3];
            double sum = 0.0;
            for (int k = 0; k < 3; ++k) {
                int v = abs(cls[ci][k]);
                int make = 0, brk = 0;
                unsigned char old = val[v];
                for (int cj : occ[v]) {
                    int before = satcnt[cj];
                    bool lit_sat = false;
                    for (int lit : cls[cj]) {
                        if (abs(lit) == v) {
                            lit_sat = (old == (lit > 0));
                            break;
                        }
                    }
                    int after = before + (lit_sat ? -1 : 1);
                    if (before == 0 && after > 0) ++make;
                    else if (before > 0 && after == 0) ++brk;
                }
                weights[k] = (1.0 + make) / pow(1.0 + brk, cb);
                sum += weights[k];
            }
            double r = rng.unit() * sum;
            int chosen = 0;
            if ((r -= weights[0]) > 0) {
                chosen = 1;
                if ((r -= weights[1]) > 0) chosen = 2;
            }
            int v = abs(cls[ci][chosen]);
            unsigned char old = val[v];
            val[v] = !old;
            for (int cj : occ[v]) {
                int before = satcnt[cj];
                bool lit_sat = false;
                for (int lit : cls[cj]) {
                    if (abs(lit) == v) {
                        lit_sat = (old == (lit > 0));
                        break;
                    }
                }
                int after = before + (lit_sat ? -1 : 1);
                satcnt[cj] = (unsigned char)after;
                if (before == 0 && after > 0) {
                    int pp = pos[cj];
                    int last = unsat.back();
                    unsat[pp] = last;
                    pos[last] = pp;
                    unsat.pop_back();
                    pos[cj] = -1;
                } else if (before > 0 && after == 0) {
                    pos[cj] = (int)unsat.size();
                    unsat.push_back(cj);
                }
            }
            if (((++total_flips) & 0xfffffLL) == 0 && timer.elapsed() >= limit) break;
        }
    }
    return false;
}

struct Cdcl {
    struct Clause {
        vector<int> lits;
        int w0 = 0;
        int w1 = 0;
        bool learnt = false;
        bool deleted = false;
    };

    int n = 0;
    vector<Clause> clauses;
    vector<vector<int>> watches;
    vector<int8_t> val;
    vector<int> level;
    vector<int> reason;
    vector<int> trail;
    vector<int> trail_lim;
    vector<double> activity;
    vector<int8_t> phase;
    int original_count = 0;
    XorShift64 rng;
    size_t qhead = 0;
    double inc = 1.0;
    long long conflicts = 0;
    ofstream proof;

    explicit Cdcl(const Formula& f, const vector<unsigned char>& initial_phase) : n(f.nvars), watches(2 * f.nvars + 2),
        val(f.nvars + 1, 0), level(f.nvars + 1, 0), reason(f.nvars + 1, -1),
        activity(f.nvars + 1, 0.0), phase(f.nvars + 1, 1),
        rng(getenv("CDCL_SEED") ? strtoull(getenv("CDCL_SEED"), nullptr, 10) : 88172645463325252ULL) {
        if ((int)initial_phase.size() == f.nvars + 1) {
            for (int v = 1; v <= f.nvars; ++v) phase[v] = initial_phase[v] ? 1 : -1;
        }
        clauses.reserve(f.clauses.size() + 100000);
        for (const auto& c : f.clauses) {
            for (int lit : c) activity[abs(lit)] += 1.0;
            add_clause(c, false);
        }
        original_count = (int)clauses.size();
    }

    int lit_index(int lit) const { return lit > 0 ? 2 * lit : 2 * (-lit) + 1; }
    int lit_value(int lit) const {
        int8_t v = val[abs(lit)];
        if (v == 0) return 0;
        return lit > 0 ? v : -v;
    }

    int add_clause(vector<int> lits, bool learnt) {
        vector<int> clean;
        vector<int8_t> seen(n + 1, 0);
        for (int lit : lits) {
            int v = abs(lit);
            int8_t s = lit > 0 ? 1 : -1;
            if (seen[v] != 0) {
                if (seen[v] != s) return -1;
                continue;
            }
            seen[v] = s;
            clean.push_back(lit);
        }
        int id = (int)clauses.size();
        Clause c;
        c.lits = std::move(clean);
        c.w0 = 0;
        c.w1 = c.lits.size() > 1 ? 1 : 0;
        c.learnt = learnt;
        clauses.push_back(std::move(c));
        if (!clauses[id].lits.empty()) {
            watches[lit_index(clauses[id].lits[clauses[id].w0])].push_back(id);
            if (clauses[id].lits.size() > 1) {
                watches[lit_index(clauses[id].lits[clauses[id].w1])].push_back(id);
            }
        }
        return id;
    }

    bool enqueue(int lit, int rsn) {
        int vv = lit_value(lit);
        if (vv > 0) return true;
        if (vv < 0) return false;
        int v = abs(lit);
        val[v] = lit > 0 ? 1 : -1;
        phase[v] = val[v];
        level[v] = (int)trail_lim.size();
        reason[v] = rsn;
        trail.push_back(lit);
        return true;
    }

    int propagate() {
        while (qhead < trail.size()) {
            int lit = trail[qhead++];
            int wi = lit_index(-lit);
            auto& ws = watches[wi];
            int out = 0;
            for (int p = 0; p < (int)ws.size(); ++p) {
                int ci = ws[p];
                Clause& c = clauses[ci];
                if (c.deleted) continue;
                int false_watch = -1;
                if (c.lits[c.w0] == -lit) false_watch = c.w0;
                else if (c.lits[c.w1] == -lit) false_watch = c.w1;
                if (false_watch < 0) {
                    ws[out++] = ci;
                    continue;
                }
                int other_watch = false_watch == c.w0 ? c.w1 : c.w0;
                int other_lit = c.lits[other_watch];
                if (lit_value(other_lit) > 0) {
                    ws[out++] = ci;
                    continue;
                }
                bool found = false;
                for (int k = 0; k < (int)c.lits.size(); ++k) {
                    if (k == c.w0 || k == c.w1) continue;
                    if (lit_value(c.lits[k]) >= 0) {
                        if (false_watch == c.w0) c.w0 = k;
                        else c.w1 = k;
                        watches[lit_index(c.lits[k])].push_back(ci);
                        found = true;
                        break;
                    }
                }
                if (found) continue;
                ws[out++] = ci;
                if (lit_value(other_lit) < 0) {
                    for (++p; p < (int)ws.size(); ++p) ws[out++] = ws[p];
                    ws.resize(out);
                    return ci;
                }
                if (!enqueue(other_lit, ci)) {
                    for (++p; p < (int)ws.size(); ++p) ws[out++] = ws[p];
                    ws.resize(out);
                    return ci;
                }
            }
            ws.resize(out);
        }
        return -1;
    }

    void backtrack(int lvl) {
        if ((int)trail_lim.size() <= lvl) return;
        for (int i = (int)trail.size() - 1; i >= trail_lim[lvl]; --i) {
            int v = abs(trail[i]);
            val[v] = 0;
            reason[v] = -1;
            level[v] = 0;
        }
        trail.resize(trail_lim[lvl]);
        trail_lim.resize(lvl);
        qhead = trail.size();
    }

    void bump(const vector<int>& learnt) {
        for (int lit : learnt) activity[abs(lit)] += inc;
        inc *= 1.05;
        if (inc > 1e90) {
            for (int v = 1; v <= n; ++v) activity[v] *= 1e-90;
            inc *= 1e-90;
        }
    }

    pair<vector<int>, int> analyze(int confl) {
        vector<int> learnt(1, 0);
        vector<unsigned char> seen(n + 1, 0);
        int path_count = 0;
        int p = 0;
        int idx = (int)trail.size() - 1;
        int ci = confl;
        do {
            Clause& c = clauses[ci];
            for (int q : c.lits) {
                if (q == p) continue;
                int v = abs(q);
                if (!seen[v] && level[v] > 0) {
                    seen[v] = 1;
                    if (level[v] == (int)trail_lim.size()) ++path_count;
                    else learnt.push_back(q);
                }
            }
            while (idx >= 0 && !seen[abs(trail[idx])]) --idx;
            if (idx < 0) break;
            p = trail[idx--];
            seen[abs(p)] = 0;
            --path_count;
            if (path_count > 0) {
                int r = reason[abs(p)];
                if (r < 0) break;
                ci = r;
            }
        } while (path_count > 0);

        learnt[0] = -p;
        int bt = 0;
        for (int i = 1; i < (int)learnt.size(); ++i) bt = max(bt, level[abs(learnt[i])]);
        bump(learnt);
        return {learnt, bt};
    }

    int pick_branch() {
        int best = 0;
        double best_act = -1.0;
        for (int v = 1; v <= n; ++v) {
            if (val[v] == 0 && activity[v] > best_act) {
                best_act = activity[v];
                best = v;
            }
        }
        if (best != 0 && rng.randint(100) < 8) {
            vector<int> pool;
            double cutoff = best_act * 0.80;
            for (int v = 1; v <= n; ++v) {
                if (val[v] == 0 && activity[v] >= cutoff) pool.push_back(v);
            }
            if (!pool.empty()) best = pool[rng.randint((int)pool.size())];
        }
        return best;
    }

    void reduce_database() {
        vector<unsigned char> locked(clauses.size(), 0);
        for (int v = 1; v <= n; ++v) {
            if (reason[v] >= 0 && reason[v] < (int)locked.size()) locked[reason[v]] = 1;
        }
        for (int ci = original_count; ci < (int)clauses.size(); ++ci) {
            Clause& c = clauses[ci];
            if (c.deleted || locked[ci] || c.lits.size() <= 2) continue;
            c.deleted = true;
            vector<int>().swap(c.lits);
        }
    }

    void write_rup(const vector<int>& lits) {
        proof << "rup ";
        if (lits.empty()) {
            proof << ">= 1 ;\n";
            return;
        }
        for (int lit : lits) proof << "1 " << (lit < 0 ? "~x" : "x") << abs(lit) << ' ';
        proof << ">= 1 ;\n";
    }

    void finish_unsat_proof() {
        proof << "output NONE ;\n";
        proof << "conclusion UNSAT : -1 ;\n";
        proof << "end pseudo-Boolean proof ;\n";
        proof.close();
    }

    int solve(const string& proof_path, double limit) {
        Timer timer;
        proof.open(proof_path);
        if (!proof) return 0;
        proof << "pseudo-Boolean proof version 3.0\n";
        long long next_restart = 100;
        long long restart_inc = 100;

        int confl = propagate();
        if (confl != -1) {
            write_rup({});
            finish_unsat_proof();
            return 20;
        }

        while (timer.elapsed() < limit) {
            confl = propagate();
            if (confl != -1) {
                ++conflicts;
                if (trail_lim.empty()) {
                    write_rup({});
                    finish_unsat_proof();
                    cerr << "c cdcl root conflict conflicts=" << conflicts << "\n";
                    return 20;
                }
                auto [learnt, bt] = analyze(confl);
                if (learnt.empty() || learnt[0] == 0) return 0;
                write_rup(learnt);
                backtrack(bt);
                int id = add_clause(learnt, true);
                if (id < 0) continue;
                enqueue(clauses[id].lits[0], id);
                if ((conflicts % 20000) == 0) reduce_database();
                if (conflicts >= next_restart) {
                    backtrack(0);
                    restart_inc = min<long long>(5000, restart_inc + 100);
                    next_restart = conflicts + restart_inc;
                }
            } else {
                int v = pick_branch();
                if (v == 0) return 10;
                trail_lim.push_back((int)trail.size());
                enqueue(phase[v] >= 0 ? v : -v, -1);
            }
        }
        proof.close();
        return 0;
    }
};

int main(int argc, char** argv) {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    if (argc != 3) {
        fprintf(stderr, "usage: solver <formula.cnf> <out.pbp>\n");
        return 1;
    }

    Formula f;
    if (!parse_dimacs(argv[1], f)) {
        cout << "c parse failure\ns UNKNOWN\n";
        return 0;
    }
    cout << "c random-mus hybrid n=" << f.nvars << " m=" << f.clauses.size() << "\n";

    double sls_limit = 60.0;
    double cdcl_limit = 120.0;
    if (const char* s = getenv("SLS_LIMIT")) sls_limit = atof(s);
    if (const char* s = getenv("CDCL_LIMIT")) cdcl_limit = atof(s);

    vector<unsigned char> model;
    if (stochastic_3sat_search(f, sls_limit, model)) {
        if (verify_model(f, model)) {
            print_model(f, model);
            return 10;
        }
        cout << "c internal model check failed\ns UNKNOWN\n";
        return 0;
    }

    Cdcl cdcl(f, model);
    int r = cdcl.solve(argv[2], cdcl_limit);
    if (r == 20) {
        cout << "s UNSATISFIABLE\n";
        return 20;
    }
    if (r == 10) {
        vector<unsigned char> val(f.nvars + 1, 0);
        for (int v = 1; v <= f.nvars; ++v) val[v] = cdcl.val[v] > 0;
        if (verify_model(f, val)) {
            print_model(f, val);
            return 10;
        }
    }
    cout << "c unsupported or search budget exhausted";
    if (cdcl.conflicts) cout << " conflicts=" << cdcl.conflicts;
    cout << "\ns UNKNOWN\n";
    return 0;
}
