题面
来源:FrontierCS 官方 statement.txt,与模型收到的题面相同。
# Max-2-SAT
## Problem
You are given a Boolean formula in CNF form, where each clause contains exactly two literals.
Your task is to assign truth values to variables to satisfy as many clauses as possible.
## Input Format
- Line 1: two integers n and m
(1 ≤ n ≤ 1000, 0 ≤ m ≤ 40000)
- Next m lines: two integers a b
- Each integer is in [-n, n], non-zero
- Positive x means variable x
- Negative -x means ¬x
Each clause is (a ∨ b).
## Output Format
- Output exactly one line:
- n integers x₁ x₂ … xₙ
- each xᵢ ∈ {0, 1}
- 1 means TRUE, 0 means FALSE
## Scoring
The physical objective is number of satisfied clauses t; larger is better. The physical reference is `a = 0.6*m`; matching a positive reference earns 60 points.
Here m is the total number of clauses.
Define the historical low-score expression (in points):
P_low = 100*t/m.
If `P_low<=60`, retain `max(0,P_low)`. For `P_low>60` and a positive physical reference and objective, award:
r = t / a
P = min(100, 60 + ln(r)).
Here `r` is the improvement factor relative to the physical reference, and `ln` is the natural logarithm with coefficient 1. In the uncapped upper branch, `r = exp(P-60)`: each additional point means an `exp(1)`-fold improvement in the physical objective. The factor is computed from the physical objective and its reference, not from a transformed reward or the old point score. Invalid output retains its existing rejection or zero score; the zero-cost exception applies only after validation. Use one score per file. Both reported ratio channels use points divided by 100. Across official files, take the arithmetic mean.
For m=0, the empty instance retains 100 points.
结果
Kimi K3.1 ProKimi
max
60.4
平均得分 ↑
- 60.4采样 1 · 部分分
- 16.7k平均输出 token(含思考) ↓
- 29.5输出速度 tokens/s ↑
- 566 秒延迟 ↓
Kimi K3.1 Pro(high)Kimi high
high
60.4
平均得分 ↑
- 60.4采样 1 · 部分分
- 7.9k平均输出 token(含思考) ↓
- 30.2输出速度 tokens/s ↑
- 264 秒延迟 ↓
DeepSeek Flash V4.1-1017DeepSeek
auto(high)
60.4
平均得分 ↑
- 60.4采样 1 · 部分分
- 19.1k平均输出 token(含思考) ↓
- 195.4输出速度 tokens/s ↑
- 98 秒延迟 ↓
MiniMax M3.1 FlashMiniMax
auto(max)
60.4
平均得分 ↑
- 60.4采样 1 · 部分分
- 51.7k平均输出 token(含思考) ↓
- 104.0输出速度 tokens/s ↑
- 498 秒延迟 ↓
↑ 越大越好,↓ 越小越好。得分 0–100,按官方时限判定,所有测试点都满分才算解出。CPU 时间 / 官方解为解出的答案在官方解最慢的 3 个测试点上的 CPU 时间之比(几何平均),只比较官方解至少需要 0.05 秒的题;复杂度按增长幂次相对官方解分类。判题与计分见 原理。
代码
Kimi K3.1 Pro · 采样 1 · 374 行
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m; if (!(cin >> n >> m)) return 0; vector<pair<int, int>> clauses(m); auto literalOf = [](int a) { int v = abs(a) - 1; return 2 * v + (a < 0); }; for (int i = 0; i < m; ++i) { int a, b; cin >> a >> b; clauses[i] = {literalOf(a), literalOf(b)}; } if (m == 0) { for (int i = 0; i < n; ++i) { if (i) cout << ' '; cout << 0; } cout << '\n'; return 0; } // First check whether all clauses can be satisfied using 2-SAT. int N = 2 * n; vector<vector<int>> g(N), rg(N); auto addImplication = [&](int a, int b) { g[a].push_back(b); rg[b].push_back(a); }; for (auto [a, b] : clauses) { addImplication(a ^ 1, b); addImplication(b ^ 1, a); } vector<int> order; order.reserve(N); vector<char> used(N, 0); function<void(int)> dfs1 = [&](int v) { used[v] = 1; for (int to : g[v]) { if (!used[to]) dfs1(to); } order.push_back(v); }; for (int v = 0; v < N; ++v) { if (!used[v]) dfs1(v); } vector<int> comp(N, -1); function<void(int, int)> dfs2 = [&](int v, int id) { comp[v] = id; for (int to : rg[v]) { if (comp[to] == -1) dfs2(to, id); } }; int componentCount = 0; for (int i = N - 1; i >= 0; --i) { int v = order[i]; if (comp[v] == -1) dfs2(v, componentCount++); } bool satisfiable = true; for (int i = 0; i < n; ++i) { if (comp[2 * i] == comp[2 * i + 1]) { satisfiable = false; break; } } if (satisfiable) { vector<uint8_t> answer(n); for (int i = 0; i < n; ++i) { answer[i] = comp[2 * i] > comp[2 * i + 1]; } bool verified = true; for (auto [a, b] : clauses) { int va = answer[a >> 1] ^ (a & 1); int vb = answer[b >> 1] ^ (b & 1); if (!(va | vb)) { verified = false; break; } } if (verified) { for (int i = 0; i < n; ++i) { if (i) cout << ' '; cout << int(answer[i]); } cout << '\n'; return 0; } } // Incremental local search for the unsatisfiable case. vector<vector<int>> adj(n); for (int c = 0; c < m; ++c) { int v1 = clauses[c].first >> 1; int v2 = clauses[c].second >> 1; adj[v1].push_back(c); if (v2 != v1) adj[v2].push_back(c); } mt19937 rng(0xC0FFEE); vector<uint8_t> x(n), bestAssignment(n); vector<int> satCount(m), unsat, positionInUnsat(m, -1); int currentScore = 0, bestScore = -1; auto literalValue = [&](int lit) -> int { return int(x[lit >> 1]) ^ (lit & 1); }; auto addUnsat = [&](int c) { positionInUnsat[c] = int(unsat.size()); unsat.push_back(c); }; auto removeUnsat = [&](int c) { int p = positionInUnsat[c]; int last = unsat.back(); unsat[p] = last; positionInUnsat[last] = p; unsat.pop_back(); positionInUnsat[c] = -1; }; auto rebuild = [&]() { unsat.clear(); fill(positionInUnsat.begin(), positionInUnsat.end(), -1); for (int c = 0; c < m; ++c) { int s = literalValue(clauses[c].first) + literalValue(clauses[c].second); satCount[c] = s; if (s == 0) addUnsat(c); } currentScore = m - int(unsat.size()); }; auto updateBest = [&]() { if (currentScore > bestScore) { bestScore = currentScore; bestAssignment = x; } }; auto calculateGain = [&](int v) { int delta = 0; for (int c : adj[v]) { int before = satCount[c]; int after = before; int a = clauses[c].first; int b = clauses[c].second; if ((a >> 1) == v) after += literalValue(a) ? -1 : 1; if ((b >> 1) == v) after += literalValue(b) ? -1 : 1; if (before == 0 && after > 0) ++delta; else if (before > 0 && after == 0) --delta; } return delta; }; auto flip = [&](int v) { x[v] ^= 1; for (int c : adj[v]) { int before = satCount[c]; int after = literalValue(clauses[c].first) + literalValue(clauses[c].second); satCount[c] = after; if (before == 0 && after > 0) { removeUnsat(c); ++currentScore; } else if (before > 0 && after == 0) { addUnsat(c); --currentScore; } } }; auto startTime = chrono::steady_clock::now(); const double TIME_LIMIT = 0.80; auto timeUp = [&]() { return chrono::duration<double>( chrono::steady_clock::now() - startTime ).count() >= TIME_LIMIT; }; vector<int> seen(n, 0); int seenToken = 0; struct QueueNode { int gain, variable, version; bool operator<(const QueueNode& other) const { return gain < other.gain; } }; auto greedyAscent = [&]() { priority_queue<QueueNode> pq; vector<int> gains(n), versions(n, 0); for (int v = 0; v < n; ++v) { gains[v] = calculateGain(v); pq.push({gains[v], v, 0}); } vector<int> affected; long long flips = 0; while (!pq.empty()) { if ((flips & 31) == 0 && timeUp()) return; QueueNode node = pq.top(); pq.pop(); int v = node.variable; if (node.version != versions[v] || node.gain != gains[v]) continue; if (node.gain <= 0) break; flip(v); updateBest(); affected.clear(); ++seenToken; auto touch = [&](int u) { if (seen[u] != seenToken) { seen[u] = seenToken; affected.push_back(u); } }; touch(v); for (int c : adj[v]) { touch(clauses[c].first >> 1); touch(clauses[c].second >> 1); } for (int u : affected) { gains[u] = calculateGain(u); ++versions[u]; pq.push({gains[u], u, versions[u]}); } ++flips; } }; // Try several inexpensive starting assignments. vector<int> positive(n, 0), negative(n, 0); for (auto [a, b] : clauses) { for (int lit : {a, b}) { if (lit & 1) ++negative[lit >> 1]; else ++positive[lit >> 1]; } } for (int v = 0; v < n; ++v) x[v] = positive[v] >= negative[v]; rebuild(); updateBest(); fill(x.begin(), x.end(), 0); rebuild(); updateBest(); fill(x.begin(), x.end(), 1); rebuild(); updateBest(); for (int rep = 0; rep < 4; ++rep) { for (int v = 0; v < n; ++v) x[v] = rng() & 1; rebuild(); updateBest(); } x = bestAssignment; rebuild(); if (!timeUp()) greedyAscent(); x = bestAssignment; rebuild(); long long iterations = 0; long long sinceImprovement = 0; long long restarts = 0; const long long maxIterations = max(300000LL, 3000LL * n); const long long stagnationLimit = max(20000LL, 40LL * n); while (iterations < maxIterations) { if ((iterations & 1023) == 0 && timeUp()) break; if (unsat.empty()) { updateBest(); break; } if (sinceImprovement >= stagnationLimit) { ++restarts; if (restarts % 6 == 0) { for (int v = 0; v < n; ++v) x[v] = rng() & 1; rebuild(); updateBest(); } else { x = bestAssignment; rebuild(); int range = max(1, n / 10); int perturbations = 1 + int(rng() % range); for (int j = 0; j < perturbations; ++j) { flip(int(rng() % n)); } updateBest(); } if (restarts % 3 == 0 && !timeUp()) greedyAscent(); sinceImprovement = 0; continue; } int c = unsat[rng() % unsat.size()]; int a = clauses[c].first; int b = clauses[c].second; int v1 = a >> 1; int v2 = b >> 1; int chosen; int noise = 150 + int(350LL * min(sinceImprovement, stagnationLimit) / stagnationLimit); if (v1 == v2) { chosen = v1; } else if (int(rng() % 1000) < noise) { chosen = (rng() & 1) ? v1 : v2; } else { int g1 = calculateGain(v1); int g2 = calculateGain(v2); if (g1 > g2) chosen = v1; else if (g2 > g1) chosen = v2; else chosen = (rng() & 1) ? v1 : v2; } flip(chosen); if (currentScore > bestScore) { updateBest(); sinceImprovement = 0; } else { ++sinceImprovement; } ++iterations; } for (int i = 0; i < n; ++i) { if (i) cout << ' '; cout << int(bestAssignment[i]); } cout << '\n'; return 0; }
Kimi K3.1 Pro(high) · 采样 1 · 299 行
#include <bits/stdc++.h> using namespace std; struct Clause { int a, b; }; struct RNG { uint64_t x = 0x9e3779b97f4a7c15ULL; uint64_t next() { x ^= x << 7; x ^= x >> 9; return x; } int get(int bound) { return bound <= 1 ? 0 : int(next() % uint64_t(bound)); } }; static int varOf(int lit) { return abs(lit) - 1; } static int nodeOf(int lit) { int v = varOf(lit); return 2 * v + (lit < 0); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m; if (!(cin >> n >> m)) return 0; vector<Clause> clauses(m); vector<vector<int>> graph(2 * n), revGraph(2 * n); for (int i = 0; i < m; ++i) { int a, b; cin >> a >> b; clauses[i] = {a, b}; int na = nodeOf(a), nb = nodeOf(b); int nna = na ^ 1, nnb = nb ^ 1; graph[nna].push_back(nb); revGraph[nb].push_back(nna); graph[nnb].push_back(na); revGraph[na].push_back(nnb); } auto printAnswer = [&](const vector<int>& assignment) { for (int i = 0; i < n; ++i) { if (i) cout << ' '; cout << assignment[i]; } cout << '\n'; }; if (m == 0) { printAnswer(vector<int>(n, 0)); return 0; } // First check whether the formula is fully satisfiable. vector<int> order, comp(2 * n, -1); order.reserve(2 * n); vector<int> iter(2 * n, 0), st; vector<char> visited(2 * n, 0); for (int s = 0; s < 2 * n; ++s) { if (visited[s]) continue; visited[s] = 1; st = {s}; while (!st.empty()) { int v = st.back(); if (iter[v] < int(graph[v].size())) { int to = graph[v][iter[v]++]; if (!visited[to]) { visited[to] = 1; st.push_back(to); } } else { order.push_back(v); st.pop_back(); } } } int componentCount = 0; for (int oi = int(order.size()) - 1; oi >= 0; --oi) { int s = order[oi]; if (comp[s] != -1) continue; st = {s}; comp[s] = componentCount; while (!st.empty()) { int v = st.back(); st.pop_back(); for (int to : revGraph[v]) { if (comp[to] == -1) { comp[to] = componentCount; st.push_back(to); } } } ++componentCount; } bool satisfiable = true; for (int i = 0; i < n; ++i) { if (comp[2 * i] == comp[2 * i + 1]) { satisfiable = false; break; } } if (satisfiable) { vector<int> answer(n); for (int i = 0; i < n; ++i) { answer[i] = comp[2 * i] > comp[2 * i + 1]; } printAnswer(answer); return 0; } auto startTime = chrono::steady_clock::now(); auto timeExpired = [&]() { return chrono::duration<double>(chrono::steady_clock::now() - startTime).count() > 0.90; }; RNG rng; vector<vector<int>> incident(n); vector<int> positiveCount(n, 0), negativeCount(n, 0); for (int i = 0; i < m; ++i) { int a = clauses[i].a, b = clauses[i].b; int va = varOf(a), vb = varOf(b); incident[va].push_back(i); if (vb != va) incident[vb].push_back(i); if (a > 0) ++positiveCount[va]; else ++negativeCount[va]; if (b > 0) ++positiveCount[vb]; else ++negativeCount[vb]; } vector<int> active; for (int i = 0; i < n; ++i) { if (!incident[i].empty()) active.push_back(i); } vector<int> value(n, 0), satCount(m, 0), gain(n, 0), tabu(n, 0); vector<int> mark(n, 0); int markStamp = 0; int score = 0; auto literalTrue = [&](int lit) { int v = varOf(lit); return value[v] == (lit > 0 ? 1 : 0); }; auto changeInTrueLiterals = [&](int ci, int v) { int delta = 0; int a = clauses[ci].a, b = clauses[ci].b; if (varOf(a) == v) delta += literalTrue(a) ? -1 : 1; if (varOf(b) == v) delta += literalTrue(b) ? -1 : 1; return delta; }; auto computeGain = [&](int v) { int result = 0; for (int ci : incident[v]) { int before = satCount[ci]; int after = before + changeInTrueLiterals(ci, v); result += int(after > 0) - int(before > 0); } return result; }; auto initializeState = [&]() { score = 0; for (int i = 0; i < m; ++i) { int cnt = int(literalTrue(clauses[i].a)) + int(literalTrue(clauses[i].b)); satCount[i] = cnt; score += cnt > 0; } for (int v : active) gain[v] = computeGain(v); fill(tabu.begin(), tabu.end(), 0); }; auto evaluate = [&](const vector<int>& assignment) { int result = 0; for (const Clause& c : clauses) { bool ta = assignment[varOf(c.a)] == (c.a > 0 ? 1 : 0); bool tb = assignment[varOf(c.b)] == (c.b > 0 ? 1 : 0); result += ta || tb; } return result; }; vector<int> bestAssignment(n, 0), majority(n, 0); for (int i = 0; i < n; ++i) { majority[i] = positiveCount[i] >= negativeCount[i]; } int bestScore = evaluate(bestAssignment); bestAssignment = vector<int>(n, 0); int majorityScore = evaluate(majority); if (majorityScore > bestScore) { bestScore = majorityScore; bestAssignment = majority; } auto flipVariable = [&](int v) { for (int ci : incident[v]) { int before = satCount[ci]; int after = before + changeInTrueLiterals(ci, v); satCount[ci] = after; score += int(after > 0) - int(before > 0); } value[v] ^= 1; vector<int> affected; ++markStamp; auto addAffected = [&](int u) { if (mark[u] != markStamp) { mark[u] = markStamp; affected.push_back(u); } }; addAffected(v); for (int ci : incident[v]) { addAffected(varOf(clauses[ci].a)); addAffected(varOf(clauses[ci].b)); } for (int u : affected) gain[u] = computeGain(u); }; int run = 0; while (!timeExpired()) { if (run == 0) { value = majority; } else if (run % 3 == 0) { value = bestAssignment; int perturbations = max(1, n / 20); for (int j = 0; j < perturbations && !active.empty(); ++j) { value[active[rng.get(int(active.size()))]] ^= 1; } } else { for (int i = 0; i < n; ++i) value[i] = int(rng.next() & 1ULL); } initializeState(); if (score > bestScore) { bestScore = score; bestAssignment = value; } int noImprovement = 0; for (int step = 1; ; ++step) { if ((step & 127) == 0 && timeExpired()) break; int chosen = -1; int chosenGain = INT_MIN; for (int v : active) { if (tabu[v] > step && score + gain[v] <= bestScore) continue; int g = gain[v]; if (g > chosenGain || (g == chosenGain && chosen != -1 && (rng.next() & 1ULL))) { chosen = v; chosenGain = g; } } if (chosen == -1) { if (active.empty()) break; chosen = active[rng.get(int(active.size()))]; } flipVariable(chosen); int tenure = 4 + rng.get(10) + min(8, noImprovement / 1000); tabu[chosen] = step + tenure; if (score > bestScore) { bestScore = score; bestAssignment = value; noImprovement = 0; } else { ++noImprovement; } if (noImprovement > 5000) break; } ++run; } printAnswer(bestAssignment); return 0; }
DeepSeek Flash V4.1-1017 · 采样 1 · 203 行
#include <bits/stdc++.h> using namespace std; int n, m; vector<int> V0, V1, D0, D1; vector<vector<int>> vc; uint32_t rng_state; inline uint32_t rnd() { rng_state ^= rng_state << 13; rng_state ^= rng_state >> 17; rng_state ^= rng_state << 5; return rng_state; } inline int contrib(int c, int w, int sat, const vector<int>& val) { int d = 0; if (V0[c] == w) { int old = (val[w] == D0[c]); d += old ? -1 : 1; } if (V1[c] == w) { int old = (val[w] == D1[c]); d += old ? -1 : 1; } int newCnt = sat + d; return (newCnt > 0) - (sat > 0); } int computeAll(vector<int>& val, vector<int>& satCnt, vector<int>& delta) { fill(delta.begin(), delta.end(), 0); int total = 0; for (int c = 0; c < m; ++c) { int cnt = (val[V0[c]] == D0[c]) + (val[V1[c]] == D1[c]); satCnt[c] = cnt; if (cnt > 0) ++total; } for (int c = 0; c < m; ++c) { int a = V0[c], b = V1[c]; int s = satCnt[c]; delta[a] += contrib(c, a, s, val); if (b != a) delta[b] += contrib(c, b, s, val); } return total; } void flipVar(int v, vector<int>& val, vector<int>& satCnt, vector<int>& delta, int& total) { for (int c : vc[v]) { int a = V0[c], b = V1[c]; int s = satCnt[c]; delta[a] -= contrib(c, a, s, val); if (b != a) delta[b] -= contrib(c, b, s, val); } val[v] ^= 1; for (int c : vc[v]) { int oldSat = (satCnt[c] > 0); int cnt = (val[V0[c]] == D0[c]) + (val[V1[c]] == D1[c]); satCnt[c] = cnt; int newSat = (cnt > 0); total += newSat - oldSat; int a = V0[c], b = V1[c]; int s = cnt; delta[a] += contrib(c, a, s, val); if (b != a) delta[b] += contrib(c, b, s, val); } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin >> n >> m; if (m == 0) { for (int i = 0; i < n; ++i) { if (i) cout << ' '; cout << 0; } cout << '\n'; return 0; } V0.resize(m); V1.resize(m); D0.resize(m); D1.resize(m); vc.assign(n, {}); for (int c = 0; c < m; ++c) { int a, b; cin >> a >> b; int va = (a > 0 ? a : -a) - 1; int vb = (b > 0 ? b : -b) - 1; int da = (a > 0) ? 1 : 0; int db = (b > 0) ? 1 : 0; V0[c] = va; V1[c] = vb; D0[c] = da; D1[c] = db; vc[va].push_back(c); if (vb != va) vc[vb].push_back(c); } rng_state = chrono::steady_clock::now().time_since_epoch().count(); if (rng_state == 0) rng_state = 123456789; const int TIME_LIMIT_MS = 850; auto start = chrono::steady_clock::now(); vector<int> bestValGlobal(n, 0); int bestTotalGlobal = -1; vector<int> val(n); vector<int> satCnt(m); vector<int> delta(n); while (true) { auto now = chrono::steady_clock::now(); if (chrono::duration_cast<chrono::milliseconds>(now - start).count() > TIME_LIMIT_MS) break; if (bestTotalGlobal < 0 || (rnd() % 100 < 20)) { for (int i = 0; i < n; ++i) val[i] = rnd() & 1; } else { val = bestValGlobal; int perturb = 1 + rnd() % (n / 20 + 1); for (int k = 0; k < perturb; ++k) { val[rnd() % n] ^= 1; } } int total = computeAll(val, satCnt, delta); if (total > bestTotalGlobal) { bestTotalGlobal = total; bestValGlobal = val; } vector<int> tabu(n, 0); int bestThis = total; int noImprove = 0; int maxIter = 20000 + n * 20; if (maxIter > 100000) maxIter = 100000; for (int iter = 1; iter <= maxIter; ++iter) { if ((iter & 1023) == 0) { auto now2 = chrono::steady_clock::now(); if (chrono::duration_cast<chrono::milliseconds>(now2 - start).count() > TIME_LIMIT_MS) break; } int bestV = -1; int bestDelta = -1000000000; for (int v = 0; v < n; ++v) { bool allowed = (tabu[v] <= iter || total + delta[v] > bestTotalGlobal); if (allowed) { if (delta[v] > bestDelta || (delta[v] == bestDelta && (rnd() & 1))) { bestDelta = delta[v]; bestV = v; } } } if (bestV == -1) { for (int v = 0; v < n; ++v) { if (delta[v] > bestDelta || (delta[v] == bestDelta && (rnd() & 1))) { bestDelta = delta[v]; bestV = v; } } } flipVar(bestV, val, satCnt, delta, total); int tenure = 5 + rnd() % 10 + n / 200; tabu[bestV] = iter + tenure; if (total > bestThis) { bestThis = total; noImprove = 0; if (total > bestTotalGlobal) { bestTotalGlobal = total; bestValGlobal = val; } } else { ++noImprove; } if (noImprove > 5000 + n * 5) break; } } for (int i = 0; i < n; ++i) { if (i) cout << ' '; cout << bestValGlobal[i]; } cout << '\n'; return 0; }
MiniMax M3.1 Flash · 采样 1 · 630 行
#include <bits/stdc++.h> using namespace std; struct RNG { uint64_t state; explicit RNG(uint64_t seed = 88172645463325252ULL) { state = seed ? seed : 88172645463325252ULL; } uint64_t next() { state ^= state >> 12; state ^= state << 25; state ^= state >> 27; return state * 2685821657736338717ULL; } int get(int n) { return n <= 0 ? 0 : static_cast<int>(next() % static_cast<uint64_t>(n)); } double real() { return static_cast<double>(next() >> 11) * (1.0 / 9007199254740992.0); } }; struct Clause { int a, b; // b == -1 denotes a unit clause int sa, sb; // +1 for a positive literal, -1 for a negative literal int weight; }; static bool solveTwoSAT( int n, const vector<pair<int, int>>& clauses, vector<int>& assignment, vector<char>* conflict = nullptr ) { const int vertices = 2 * n; vector<vector<int>> graph(vertices), reverseGraph(vertices); auto literalNode = [](int literal) { int variable = abs(literal) - 1; return 2 * variable + (literal < 0); }; auto addEdge = [&](int from, int to) { graph[from].push_back(to); reverseGraph[to].push_back(from); }; for (auto [a, b] : clauses) { if (a == -b) continue; int u = literalNode(a); int v = literalNode(b); addEdge(u ^ 1, v); addEdge(v ^ 1, u); } vector<char> visited(vertices, false); vector<int> order; order.reserve(vertices); auto dfs1 = [&](auto&& self, int vertex) -> void { visited[vertex] = true; for (int to : graph[vertex]) { if (!visited[to]) self(self, to); } order.push_back(vertex); }; for (int vertex = 0; vertex < vertices; ++vertex) { if (!visited[vertex]) dfs1(dfs1, vertex); } vector<int> component(vertices, -1); int componentCount = 0; auto dfs2 = [&](auto&& self, int vertex, int id) -> void { component[vertex] = id; for (int to : reverseGraph[vertex]) { if (component[to] == -1) self(self, to, id); } }; for (int i = static_cast<int>(order.size()) - 1; i >= 0; --i) { int vertex = order[i]; if (component[vertex] == -1) { dfs2(dfs2, vertex, componentCount++); } } if (conflict) conflict->assign(n, false); bool satisfiable = true; for (int variable = 0; variable < n; ++variable) { if (component[2 * variable] == component[2 * variable + 1]) { satisfiable = false; if (conflict) (*conflict)[variable] = true; } } assignment.assign(n, 0); if (satisfiable) { for (int variable = 0; variable < n; ++variable) { assignment[variable] = component[2 * variable] > component[2 * variable + 1]; } } return satisfiable; } class MaxTwoSATHeuristic { public: struct StoredClause { int a, b; int sa, sb; int weight; }; int n; vector<StoredClause> clauses; vector<vector<int>> adjacency; vector<int> value; vector<int> bestValue; long long work = 0; long long workLimit = 30000000LL; int bestUnsatisfied = INT_MAX; private: vector<int> unsatisfied; vector<int> position; vector<int> lastPicked; vector<int> makeRaw, breakRaw; vector<long long> makeWeighted, breakWeighted; static constexpr int MAX_WEIGHT = 5000; bool literalTrue(int variable, int sign) const { return sign > 0 ? value[variable] != 0 : value[variable] == 0; } void addUnsatisfied(int id) { position[id] = static_cast<int>(unsatisfied.size()); unsatisfied.push_back(id); } void removeUnsatisfied(int id) { int index = position[id]; int last = static_cast<int>(unsatisfied.size()) - 1; if (index != last) { int moved = unsatisfied[last]; unsatisfied[index] = moved; position[moved] = index; } unsatisfied.pop_back(); position[id] = -1; } public: double averageIncidence() const { long long incidences = 0; for (const auto& clause : clauses) { incidences += 1 + (clause.b != -1); } return max(1.0, static_cast<double>(incidences) / max(1, n)); } explicit MaxTwoSATHeuristic(int variableCount, vector<StoredClause> input) : n(variableCount), clauses(std::move(input)) { adjacency.assign(n, {}); position.assign(clauses.size(), -1); lastPicked.assign(clauses.size(), -1000000000); value.assign(n, 0); bestValue.assign(n, 0); makeRaw.assign(n, 0); breakRaw.assign(n, 0); makeWeighted.assign(n, 0); breakWeighted.assign(n, 0); unsatisfied.reserve(clauses.size()); for (int id = 0; id < static_cast<int>(clauses.size()); ++id) { adjacency[clauses[id].a].push_back(id); if (clauses[id].b != -1) { adjacency[clauses[id].b].push_back(id); } } } bool considerCurrent() { if (static_cast<int>(unsatisfied.size()) < bestUnsatisfied) { bestUnsatisfied = static_cast<int>(unsatisfied.size()); bestValue = value; return true; } return false; } bool loadAssignment(const vector<int>& assignment) { value = assignment; fill(makeRaw.begin(), makeRaw.end(), 0); fill(breakRaw.begin(), breakRaw.end(), 0); fill(makeWeighted.begin(), makeWeighted.end(), 0); fill(breakWeighted.begin(), breakWeighted.end(), 0); fill(position.begin(), position.end(), -1); fill(lastPicked.begin(), lastPicked.end(), -1000000000); unsatisfied.clear(); for (auto& clause : clauses) clause.weight = 1; for (int id = 0; id < static_cast<int>(clauses.size()); ++id) { const auto& clause = clauses[id]; bool trueA = literalTrue(clause.a, clause.sa); bool trueB = clause.b != -1 && literalTrue(clause.b, clause.sb); if (!trueA && !trueB) { ++makeRaw[clause.a]; makeWeighted[clause.a] += clause.weight; if (clause.b != -1) { ++makeRaw[clause.b]; makeWeighted[clause.b] += clause.weight; } addUnsatisfied(id); } else { if (trueA && !trueB) { ++breakRaw[clause.a]; breakWeighted[clause.a] += clause.weight; } else if (!trueA && trueB) { ++breakRaw[clause.b]; breakWeighted[clause.b] += clause.weight; } } } return considerCurrent(); } void flip(int variable) { work += static_cast<long long>(adjacency[variable].size()); for (int id : adjacency[variable]) { auto& clause = clauses[id]; bool oldA = literalTrue(clause.a, clause.sa); bool oldB = clause.b != -1 && literalTrue(clause.b, clause.sb); bool newA = clause.a == variable ? !oldA : oldA; bool newB = clause.b != -1 && (clause.b == variable ? !oldB : oldB); int oldMakeA = !oldA && !oldB; int oldBreakA = oldA && !oldB; int newMakeA = !newA && !newB; int newBreakA = newA && !newB; makeRaw[clause.a] += newMakeA - oldMakeA; breakRaw[clause.a] += newBreakA - oldBreakA; makeWeighted[clause.a] += 1LL * (newMakeA - oldMakeA) * clause.weight; breakWeighted[clause.a] += 1LL * (newBreakA - oldBreakA) * clause.weight; if (clause.b != -1) { int oldMakeB = !oldB && !oldA; int oldBreakB = oldB && !oldA; int newMakeB = !newB && !newA; int newBreakB = newB && !oldA; makeRaw[clause.b] += newMakeB - oldMakeB; breakRaw[clause.b] += newBreakB - oldBreakB; makeWeighted[clause.b] += 1LL * (newMakeB - oldMakeB) * clause.weight; breakWeighted[clause.b] += 1LL * (newBreakB - oldBreakB) * clause.weight; } bool oldSatisfied = oldA || oldB; bool newSatisfied = newA || newB; if (oldSatisfied != newSatisfied) { if (newSatisfied) { removeUnsatisfied(id); } else { addUnsatisfied(id); } } if (oldSatisfied && !newSatisfied && clause.b != -1 && clause.weight < MAX_WEIGHT) { ++clause.weight; ++makeWeighted[clause.a]; ++makeWeighted[clause.b]; } } value[variable] ^= 1; } void hillClimb() { while (work < workLimit && !unsatisfied.empty()) { int bestVariable = -1; int bestGain = 0; long long bestTie = LLONG_MIN; for (int variable = 0; variable < n; ++variable) { int gain = makeRaw[variable] - breakRaw[variable]; if (gain <= 0) continue; long long tie = makeWeighted[variable] - breakWeighted[variable]; if (gain > bestGain || (gain == bestGain && tie > bestTie)) { bestGain = gain; bestTie = tie; bestVariable = variable; } } if (bestVariable == -1) break; flip(bestVariable); considerCurrent(); } } int pickClause(int iteration, RNG& random) { int size = static_cast<int>(unsatisfied.size()); int chosen = unsatisfied[random.get(size)]; if (size >= 8) { for (int sample = 0; sample < 2; ++sample) { int candidate = unsatisfied[random.get(size)]; int chosenAge = iteration - lastPicked[chosen]; int candidateAge = iteration - lastPicked[candidate]; if (clauses[candidate].weight > clauses[chosen].weight || (clauses[candidate].weight == clauses[chosen].weight && candidateAge > chosenAge)) { chosen = candidate; } } } lastPicked[chosen] = iteration; return chosen; } void reweightUnsatisfiedClauses() { work += 2LL * unsatisfied.size(); for (int id : unsatisfied) { auto& clause = clauses[id]; if (clause.b != -1 && clause.weight < MAX_WEIGHT) { ++clause.weight; ++makeWeighted[clause.a]; ++makeWeighted[clause.b]; } } } void walk(int maxFlips, int noisePerMille, RNG& random) { if (unsatisfied.empty()) { considerCurrent(); return; } considerCurrent(); int stale = 0; int reweightEvery = max(2000, static_cast<int>(10 * averageIncidence())); for (int iteration = 0; iteration < maxFlips && work < workLimit && !unsatisfied.empty(); ++iteration) { int id = pickClause(iteration, random); const auto& clause = clauses[id]; int chosen = clause.a; if (clause.b != -1) { long long scoreA = makeWeighted[clause.a] - breakWeighted[clause.a]; long long scoreB = makeWeighted[clause.b] - breakWeighted[clause.b]; bool chooseB; if (random.get(1000) < noisePerMille) { chooseB = random.get(2) != 0; } else if (scoreA == scoreB) { chooseB = random.get(2) != 0; } else { chooseB = scoreB > scoreA; } if (chooseB) chosen = clause.b; } int previousBest = bestUnsatisfied; flip(chosen); bool improved = considerCurrent(); if (bestUnsatisfied < previousBest) { stale = 0; } else { ++stale; } if (stale >= reweightEvery) { reweightUnsatisfiedClauses(); stale = 0; } } hillClimb(); } void perturb(int count, RNG& random) { if (count <= 0 || clauses.empty()) return; vector<char> seen(n, false), chosen(n, false); vector<int> hot, all; for (int id : unsatisfied) { const auto& clause = clauses[id]; if (!seen[clause.a]) { seen[clause.a] = true; hot.push_back(clause.a); } if (clause.b != -1 && !seen[clause.b]) { seen[clause.b] = true; hot.push_back(clause.b); } } fill(seen.begin(), seen.end(), false); for (int variable = 0; variable < n; ++variable) { if (!adjacency[variable].empty()) { seen[variable] = true; all.push_back(variable); } } auto pickUnused = [&](const vector<int>& candidates) { for (int attempt = 0; attempt < static_cast<int>(candidates.size()); ++attempt) { int candidate = candidates[random.get(candidates.size())]; if (!chosen[candidate]) return candidate; } return -1; }; for (int step = 0; step < count && work < workLimit; ++step) { int variable = -1; if (!hot.empty() && random.get(100) < 75) { variable = pickUnused(hot); } if (variable == -1) { variable = pickUnused(all); } if (variable == -1) break; chosen[variable] = true; flip(variable); } } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m; cin >> n >> m; vector<pair<int, int>> inputClauses(m); for (auto& [a, b] : inputClauses) { cin >> a >> b; } vector<int> twoSATAssignment; vector<char> conflict; bool satisfiable = solveTwoSAT(n, inputClauses, twoSATAssignment, &conflict); if (satisfiable) { for (int variable = 0; variable < n; ++variable) { if (variable) cout << ' '; cout << twoSATAssignment[variable]; } cout << '\n'; return 0; } vector<MaxTwoSATHeuristic::StoredClause> clauses; clauses.reserve(m); for (auto [a, b] : inputClauses) { if (a == -b) continue; int variableA = abs(a) - 1; int signA = a > 0 ? 1 : -1; if (abs(a) == abs(b)) { clauses.push_back({variableA, -1, signA, 1, 1}); } else { int variableB = abs(b) - 1; int signB = b > 0 ? 1 : -1; clauses.push_back({variableA, variableB, signA, signB, 1}); } } if (clauses.empty()) { for (int variable = 0; variable < n; ++variable) { if (variable) cout << ' '; cout << 0; } cout << '\n'; return 0; } uint64_t seed = 0x9E3779B97F4A7C15ULL ^ (static_cast<uint64_t>(n) << 32) ^ static_cast<uint64_t>(m); RNG random(seed); MaxTwoSATHeuristic solver(n, std::move(clauses)); long long computedLimit = 700LL * static_cast<long long>(solver.clauses.size()) + 50LL * n; solver.workLimit = min(30000000LL, max(4000000LL, computedLimit)); vector<int> polarity(n, 0); for (const auto& clause : solver.clauses) { polarity[clause.a] += clause.sa; if (clause.b != -1) polarity[clause.b] += clause.sb; } vector<int> majority(n, 0); for (int variable = 0; variable < n; ++variable) { if (polarity[variable] > 0) { majority[variable] = 1; } else if (polarity[variable] < 0) { majority[variable] = 0; } else { majority[variable] = random.get(2); } } vector<int> sccSeed = twoSATAssignment; for (int variable = 0; variable < n; ++variable) { if (conflict[variable]) { sccSeed[variable] = random.get(2); } } long long phase1End = static_cast<long long>(solver.workLimit * 0.62); long long phase2End = static_cast<long long>(solver.workLimit * 0.82); const int noise[] = {140, 220, 300, 380, 180, 280}; for (int round = 0; round < 6 && solver.work < phase1End; ++round) { if (round < 4) { vector<int> seed; if (round == 0) { seed = sccSeed; } else if (round == 1) { seed = majority; } else { seed.assign(n, 0); for (int variable = 0; variable < n; ++variable) { seed[variable] = random.get(2); } } solver.loadAssignment(seed); } else { solver.loadAssignment(solver.bestValue); solver.perturb(4 + random.get(8), random); solver.considerCurrent(); } int remainingRounds = 6 - round; long long allowance = (phase1End - solver.work) / remainingRounds; long long flips = allowance / max(1LL, static_cast<long long>(solver.averageIncidence())); flips = max(3000LL, min(70000LL, flips)); solver.walk(static_cast<int>(flips), noise[round], random); if (solver.bestUnsatisfied == 0) break; } int trials = 0; while (solver.work < phase2End && trials < 400 && solver.bestUnsatisfied > 0) { solver.loadAssignment(solver.bestValue); solver.perturb(3 + random.get(10), random); solver.considerCurrent(); if ((trials & 3) == 3) { solver.walk(1200, 350, random); } else { solver.hillClimb(); } ++trials; } if (solver.bestUnsatisfied > 0) { solver.loadAssignment(solver.bestValue); long long remaining = solver.workLimit - solver.work; long long flips = remaining / max(1LL, static_cast<long long>(solver.averageIncidence())); flips = max(1000LL, min(250000LL, flips)); solver.walk(static_cast<int>(flips), 230, random); } solver.loadAssignment(solver.bestValue); solver.hillClimb(); for (int variable = 0; variable < n; ++variable) { if (variable) cout << ' '; cout << solver.bestValue[variable]; } cout << '\n'; return 0; }