题面
来源:FrontierCS 官方 statement.txt,与模型收到的题面相同。
DNA Matching
Time Limit: 2 s
Memory Limit: 512 MB
A string s is called a “DNA sequence” if and only if s consists only of the characters A, C, G, T.
You are given m strings s1, s2, ..., sm, each of length n, and each of them consists only of the characters A, C, G, T, ?.
For a DNA sequence t of length n, we call t valid if and only if there exists an index i (1 ≤ i ≤ m) and a way to replace each ? in si by one of A,C,G,T, so that after replacement the resulting string s_i' is exactly equal to t.
You need to compute the probability that a randomly chosen DNA sequence t (of length n, where each of the 4^n possible DNA sequences is equally likely) is valid.
Input Format
The first line contains two positive integers n, m.
Then follow m lines, each line contains a string si of length n. It is guaranteed that each si only uses characters from A, C, G, T, ?.
Output Format
Output one real number — the probability. Make sure the number is precise enough.
Sample 1
input
3 1
AC?
output
0.0625
Sample 2
input
6 2
AC??A?
A??A?T
output
0.0302734375
## Scoring
All feasibility and interaction limits apply before scoring; invalid output receives zero. Points are averaged over test files. For the logarithmic branch, write x for the original minimizing quantity and a for its physical 60-point reference. The improvement factor is r=a/x, and the upper-band award is P=min(100,60+ln(r)). Here ln is natural: r=1 corresponds to 60 points, and on the uncapped logarithmic upper band, r=exp(P-60). Each additional point multiplies the physical improvement factor by e (divides a minimizing objective by e or multiplies a maximizing objective by e, as applicable). The lower-band, zero-objective, and completion rules below still apply.
p is the output probability and p_ref is the stored reference probability. When p_ref is nonzero, E=abs(p/p_ref-1). Define the objective x=E, its physical reference a=A=0.04, and the lower-band calculation L=100*max(0,1-10*E).
If p_ref=0, output p=0 receives 100 and every nonzero p receives zero; the following rule applies only when p_ref is nonzero.
```text
P = 100, if x <= 1e-9
P = L, if L <= 60 and x > 1e-9
P = min(100, 60 + ln(r)), otherwise
```
Relative error at most 1e-9 is treated as zero before the lower-band test. This numerical tolerance avoids requiring the exact rounding of the stored floating-point reference. For example, the stored value 0.0052510053510665894 and the rounded output 0.005251005351 both receive 100 points. The tolerance is relative, so outputting zero for a small nonzero reference does not receive full credit. Errors above this tolerance retain the scoring curve above. The checker reports P/100.
结果
Kimi K3.1 ProKimi
max
19.9
平均得分 ↑
- 19.9采样 1 · 部分分
- 19.9k平均输出 token(含思考) ↓
- 31.7输出速度 tokens/s ↑
- 629 秒延迟 ↓
Kimi K3.1 Pro(high)Kimi high
high
28.1
平均得分 ↑
- 28.1采样 1 · 部分分
- 4.9k平均输出 token(含思考) ↓
- 26.4输出速度 tokens/s ↑
- 190 秒延迟 ↓
DeepSeek Flash V4.1-1017DeepSeek
auto(high)
0.0
平均得分 ↑
- 0.0采样 1 · 无代码
- 57.3k平均输出 token(含思考) ↓
- 203.4输出速度 tokens/s ↑
- 282 秒延迟 ↓
MiniMax M3.1 FlashMiniMax
auto(max)
0.0
平均得分 ↑
- 0.0采样 1 · 编译错误
- 79.3k平均输出 token(含思考) ↓
- 85.1输出速度 tokens/s ↑
- 932 秒延迟 ↓
↑ 越大越好,↓ 越小越好。得分 0–100,按官方时限判定,所有测试点都满分才算解出。CPU 时间 / 官方解为解出的答案在官方解最慢的 3 个测试点上的 CPU 时间之比(几何平均),只比较官方解至少需要 0.05 秒的题;复杂度按增长幂次相对官方解分类。判题与计分见 原理。
代码
Kimi K3.1 Pro · 采样 1 · 123 行
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m; cin >> n >> m; vector<string> s(m); for (string &x : s) cin >> x; const int N = 1 << m; vector<int> wildCount(N, 0); vector<unsigned char> bad(N, 0); auto letterId = [](char c) { if (c == 'A') return 0; if (c == 'C') return 1; if (c == 'G') return 2; return 3; }; vector<array<unsigned long long, 4>> positionBits(m); for (int base = 0; base < n; base += 64) { for (auto &a : positionBits) a.fill(0); int len = min(64, n - base); for (int offset = 0; offset < len; ++offset) { int pos = base + offset; int wildMask = 0; unsigned long long bit = 1ULL << offset; for (int i = 0; i < m; ++i) { char c = s[i][pos]; if (c == '?') { wildMask |= 1 << i; } else { positionBits[i][letterId(c)] |= bit; } } ++wildCount[wildMask]; } for (int i = 0; i < m; ++i) { for (int j = i + 1; j < m; ++j) { int pairMask = (1 << i) | (1 << j); if (bad[pairMask]) continue; bool conflict = false; for (int a = 0; a < 4 && !conflict; ++a) { for (int b = 0; b < 4; ++b) { if (a != b && (positionBits[i][a] & positionBits[j][b])) { conflict = true; break; } } } if (conflict) bad[pairMask] = 1; } } } for (int b = 0; b < m; ++b) { int bit = 1 << b; for (int start = 0; start < N; start += 2 * bit) { for (int offset = 0; offset < bit; ++offset) { int low = start + offset; int high = low + bit; wildCount[low] += wildCount[high]; bad[high] |= bad[low]; } } } int maxWild = 0; for (int i = 0; i < m; ++i) { maxWild = max(maxWild, wildCount[1 << i]); } long double sum = 0.0L; long double compensation = 0.0L; auto addTerm = [&](long double value) { long double next = sum + value; if (fabsl(sum) >= fabsl(value)) { compensation += (sum - next) + value; } else { compensation += (value - next) + sum; } sum = next; }; for (int mask = 1; mask < N; ++mask) { if (bad[mask]) continue; int difference = maxWild - wildCount[mask]; if (difference > 20000) continue; long double term = ldexp(1.0L, -2 * difference); if (__builtin_popcount((unsigned)mask) % 2 == 0) { term = -term; } addTerm(term); } sum += compensation; int scale = n - maxWild; long double logProbability = log10(sum) - (long double)scale * log10(4.0L); long long exponent = (long long)floor(logProbability); long double mantissa = pow(10.0L, logProbability - (long double)exponent); cout << fixed << setprecision(17) << mantissa << 'e' << exponent << '\n'; return 0; }
Kimi K3.1 Pro(high) · 采样 1 · 66 行
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m; cin >> n >> m; vector<string> s(m); for (auto &pattern : s) { cin >> pattern; if (pattern.find_first_not_of('?') == string::npos) { cout << "1\n"; return 0; } } vector<long double> invPow4(n + 1); invPow4[0] = 1.0L; for (int i = 1; i <= n; ++i) { invPow4[i] = invPow4[i - 1] / 4.0L; } long double answer = 0.0L; string current(n, '?'); function<void(int, int, int, const string &)> dfs = [&](int pos, int wildcards, int taken, const string &state) { if (pos == m) return; string next = state; int nextWildcards = wildcards; bool compatible = true; for (int j = 0; j < n; ++j) { char c = s[pos][j]; if (c == '?') continue; if (next[j] == '?') { next[j] = c; --nextWildcards; } else if (next[j] != c) { compatible = false; break; } } if (compatible) { long double term = invPow4[n - nextWildcards]; if (taken % 2 == 0) answer += term; else answer -= term; dfs(pos + 1, nextWildcards, taken + 1, next); } dfs(pos + 1, wildcards, taken, state); }; dfs(0, n, 0, current); answer = max(0.0L, min(1.0L, answer)); cout << setprecision(20) << answer << '\n'; return 0; }
没有代码:回答中没有代码块。
MiniMax M3.1 Flash · 采样 1 · 1022 行
#include <bits/stdc++.h> #include <boost/multiprecision/cpp_int.hpp> using namespace std; using boost::multiprecision::cpp_int; using ld = long double; using ull = unsigned long long; static constexpr ld LN2 = 0.693147180559945309417232121458176568L; static constexpr ld LN10 = 2.302585092994045684017991454684364208L; static const ld NEG_INF = -numeric_limits<ld>::infinity(); struct U64Hash { static ull splitmix64(ull x) { x += 0x9e3779b97f4a7c15ULL; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL; x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL; return x ^ (x >> 31); } size_t operator()(ull x) const { return splitmix64(x); } }; static int nucleotideCode(char c) { if (c == 'A') return 0; if (c == 'C') return 1; if (c == 'G') return 2; return 3; } static ld logBigInteger(const cpp_int& x) { unsigned b = boost::multiprecision::msb(x); unsigned shift = b >= 63 ? b - 63 : 0; cpp_int shifted = x >> shift; ull top = shifted.convert_to<ull>(); return (ld)shift * LN2 + logl((ld)top); } static ld logSumExp(const vector<ld>& values) { ld maximum = NEG_INF; for (ld x : values) maximum = max(maximum, x); if (maximum == NEG_INF) return NEG_INF; ld sum = 0; for (ld x : values) { if (x != NEG_INF) sum += expl(x - maximum); } return maximum + logl(sum); } static void printProbability(ld logProbability) { if (logProbability > 0 && logProbability < 1e-15L) logProbability = 0; if (logProbability < 0 && logProbability > -1e-15L) logProbability = 0; ld logarithm = logProbability / LN10; long long exponent = (long long)floorl(logarithm); ld fraction = logarithm - (ld)exponent; ld mantissa = expl(fraction * LN10); if (mantissa < 1.0L) { mantissa *= 10.0L; --exponent; } if (mantissa >= 10.0L) { mantissa /= 10.0L; ++exponent; } cout << scientific << setprecision(20) << mantissa << 'e' << exponent << '\n'; } struct Pattern { string s; vector<int> fixedPositions; }; static vector<Pattern> removeRedundantPatterns(vector<Pattern> patterns) { int m = (int)patterns.size(); unordered_map<ull, vector<int>, U64Hash> byPositionAndCharacter; byPositionAndCharacter.reserve((size_t)m * 2 + 1); for (int i = 0; i < m; ++i) { for (int position : patterns[i].fixedPositions) { ull key = ((ull)position << 2) | (ull)nucleotideCode(patterns[i].s[position]); byPositionAndCharacter[key].push_back(i); } } for (auto& entry : byPositionAndCharacter) { auto& ids = entry.second; sort(ids.begin(), ids.end()); } vector<unsigned char> redundant(m, false); vector<int> mark(m, 0); int stamp = 0; ull budget = 40000000ULL; bool exhausted = false; for (int i = 0; i < m && !exhausted; ++i) { const auto& fixed = patterns[i].fixedPositions; if (fixed.empty()) continue; ull chosenKey = 0; size_t smallest = numeric_limits<size_t>::max(); for (int position : fixed) { ull key = ((ull)position << 2) | (ull)nucleotideCode(patterns[i].s[position]); size_t size = byPositionAndCharacter[key].size(); if (size < smallest) { smallest = size; chosenKey = key; } } vector<int> candidates = byPositionAndCharacter[chosenKey]; for (int position : fixed) { ull key = ((ull)position << 2) | (ull)nucleotideCode(patterns[i].s[position]); if (key == chosenKey) continue; const auto& group = byPositionAndCharacter[key]; if (budget < candidates.size()) { exhausted = true; break; } budget -= candidates.size(); if (group.size() < candidates.size()) { ++stamp; for (int id : group) mark[id] = stamp; vector<int> filtered; filtered.reserve(candidates.size()); for (int id : candidates) { if (mark[id] == stamp) filtered.push_back(id); } candidates.swap(filtered); } else { vector<int> filtered; filtered.reserve(candidates.size()); for (int id : candidates) { if (binary_search(group.begin(), group.end(), id)) { filtered.push_back(id); } } candidates.swap(filtered); } if (candidates.empty()) break; } if (exhausted) break; for (int id : candidates) { if (id != i) { redundant[i] = true; break; } } } vector<Pattern> result; result.reserve(m); for (int i = 0; i < m; ++i) { if (!redundant[i]) result.push_back(move(patterns[i])); } return result; } struct DSU { vector<int> parent, size; explicit DSU(int n) : parent(n), size(n, 1) { iota(parent.begin(), parent.end(), 0); } int find(int x) { while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; } void unite(int a, int b) { a = find(a); b = find(b); if (a == b) return; if (size[a] < size[b]) swap(a, b); parent[b] = a; size[a] += size[b]; } }; struct ProbabilityResult { ld logValid = 0; ld logInvalid = 0; }; static ProbabilityResult probabilityFromLogValid(ld logValid) { ProbabilityResult result; result.logValid = logValid; if (logValid >= 0) { result.logInvalid = NEG_INF; } else { ld p = expl(logValid); if (p <= 0) { result.logInvalid = 0; } else if (p < 0.5L) { result.logInvalid = log1pl(-p); } else { ld q = -expm1l(logValid); result.logInvalid = logl(q); } } return result; } static ProbabilityResult exactInclusionExclusion( const vector<string>& patterns ) { int m = (int)patterns.size(); int n = (int)patterns[0].size(); uint32_t subsetCount = 1U << m; uint32_t fullMask = subsetCount - 1; vector<array<uint32_t, 4>> masks(n); for (auto& mask : masks) mask.fill(0); for (int i = 0; i < m; ++i) { uint32_t bit = 1U << i; for (int position = 0; position < n; ++position) { if (patterns[i][position] != '?') { masks[position][nucleotideCode(patterns[i][position])] |= bit; } } } vector<uint32_t> conflict(m, 0); for (int position = 0; position < n; ++position) { for (int c1 = 0; c1 < 4; ++c1) { for (int c2 = c1 + 1; c2 < 4; ++c2) { uint32_t first = masks[position][c1]; uint32_t second = masks[position][c2]; if (!first || !second) continue; uint32_t bits = first; while (bits) { int i = __builtin_ctz(bits); bits &= bits - 1; conflict[i] |= second; } bits = second; while (bits) { int i = __builtin_ctz(bits); bits &= bits - 1; conflict[i] |= first; } } } } vector<uint32_t> subsetFree(subsetCount, 0); int relevantPositions = 0; for (int position = 0; position < n; ++position) { uint32_t mask = masks[position][0] | masks[position][1] | masks[position][2] | masks[position][3]; if (mask) { ++subsetFree[mask]; ++relevantPositions; } } for (uint32_t bit = 1; bit < subsetCount; bit <<= 1) { uint32_t step = bit << 1; for (uint32_t base = 0; base < subsetCount; base += step) { for (uint32_t offset = 0; offset < bit; ++offset) { subsetFree[base + bit + offset] += subsetFree[base + offset]; } } } vector<long long> coefficient(relevantPositions + 1, 0); auto dfs = [&](auto&& self, int first, uint32_t selected, bool odd) -> void { if (selected) { uint32_t freePositions = subsetFree[fullMask ^ selected]; int fixedPositions = relevantPositions - (int)freePositions; coefficient[fixedPositions] += odd ? 1 : -1; } for (int i = first; i < m; ++i) { if (conflict[i] & selected) continue; self(self, i + 1, selected | (1U << i), !odd); } }; dfs(dfs, 0, 0, false); int maximumDegree = relevantPositions; while (maximumDegree > 0 && coefficient[maximumDegree] == 0) { --maximumDegree; } cpp_int validNumerator = 0; for (int degree = 0; degree <= maximumDegree; ++degree) { validNumerator <<= 2; validNumerator += coefficient[degree]; } cpp_int totalNumerator = cpp_int(1) << (2ULL * maximumDegree); cpp_int invalidNumerator = totalNumerator - validNumerator; ProbabilityResult result; result.logValid = logBigInteger(validNumerator) - 2.0L * maximumDegree * LN2; if (invalidNumerator == 0) { result.logInvalid = NEG_INF; } else { result.logInvalid = logBigInteger(invalidNumerator) - 2.0L * maximumDegree * LN2; } return result; } struct TooComplex {}; struct TrieNode { array<int, 5> next; int depth; int terminals; explicit TrieNode(int depth = 0) : next{-1, -1, -1, -1, -1}, depth(depth), terminals(0) {} }; struct PatternTrie { int length; vector<TrieNode> nodes; explicit PatternTrie(int length) : length(length), nodes(1) {} void insert(const string& pattern) { int node = 0; for (int depth = 0; depth < length; ++depth) { int edge = pattern[depth] == '?' ? 4 : nucleotideCode(pattern[depth]); int nextNode = nodes[node].next[edge]; if (nextNode == -1) { if (nodes.size() >= 4000000) throw TooComplex{}; nextNode = (int)nodes.size(); nodes[node].next[edge] = nextNode; nodes.emplace_back(depth + 1); } node = nextNode; } ++nodes[node].terminals; } bool matches(const string& value) const { vector<int> stack; stack.reserve(64); stack.push_back(0); while (!stack.empty()) { int node = stack.back(); stack.pop_back(); int depth = nodes[node].depth; if (depth == length) { if (nodes[node].terminals) return true; continue; } int exact = nodes[node].next[nucleotideCode(value[depth])]; int wildcard = nodes[node].next[4]; if (exact != -1) stack.push_back(exact); if (wildcard != -1) stack.push_back(wildcard); } return false; } int countMatches(const string& value) const { vector<int> stack; stack.reserve(64); stack.push_back(0); int answer = 0; while (!stack.empty()) { int node = stack.back(); stack.pop_back(); int depth = nodes[node].depth; if (depth == length) { answer += nodes[node].terminals; continue; } int exact = nodes[node].next[nucleotideCode(value[depth])]; int wildcard = nodes[node].next[4]; if (exact != -1) stack.push_back(exact); if (wildcard != -1) stack.push_back(wildcard); } return answer; } }; static bool exactSmallComponent( const vector<string>& patterns, ProbabilityResult& result ) { int n = (int)patterns[0].size(); if (n > 10) return false; PatternTrie trie(n); try { for (const string& pattern : patterns) trie.insert(pattern); } catch (const TooComplex&) { return false; } uint32_t total = 1U << (2 * n); uint32_t valid = 0; string value(n, 'A'); const string alphabet = "ACGT"; for (uint32_t code = 0; code < total; ++code) { uint32_t x = code; for (int position = n - 1; position >= 0; --position) { value[position] = alphabet[x & 3]; x >>= 2; } if (trie.matches(value)) ++valid; } result.logValid = logl((ld)valid) - 2.0L * n * LN2; result.logInvalid = logl((ld)(total - valid)) - 2.0L * n * LN2; return true; } struct BDDNode { int variable; array<int, 4> child; }; struct BDDUniqueKey { ull first; ull second; uint32_t variable; bool operator==(const BDDUniqueKey& other) const { return first == other.first && second == other.second && variable == other.variable; } }; struct BDDUniqueHash { static ull rotateLeft(ull x, int amount) { return (x << amount) | (x >> (64 - amount)); } size_t operator()(const BDDUniqueKey& key) const { ull value = key.first ^ rotateLeft(key.second, 23) ^ ((ull)key.variable * 0x9e3779b97f4a7c15ULL); return U64Hash::splitmix64(value); } }; class BDD { public: BDD() { nodes.reserve(1024); nodes.push_back({-1, {0, 0, 0, 0}}); nodes.push_back({-1, {0, 0, 0, 0}}); } int buildPattern(const string& pattern) { int suffix = 1; for (int position = (int)pattern.size() - 1; position >= 0; --position) { array<int, 4> child{0, 0, 0, 0}; if (pattern[position] == '?') { child.fill(suffix); } else { child[nucleotideCode(pattern[position])] = suffix; } suffix = makeNode(position, child); } return suffix; } int unite(int a, int b) { if (a == b) return a; if (a == 0) return b; if (b == 0) return a; if (a == 1 || b == 1) return 1; if (a > b) swap(a, b); ull key = ((ull)(uint32_t)a << 32) | (uint32_t)b; auto found = applyMemo.find(key); if (found != applyMemo.end()) return found->second; int variable = min(nodes[a].variable, nodes[b].variable); array<int, 4> child; for (int c = 0; c < 4; ++c) { int left = nodes[a].variable == variable ? nodes[a].child[c] : a; int right = nodes[b].variable == variable ? nodes[b].child[c] : b; child[c] = unite(left, right); } int result = makeNode(variable, child); if (applyMemo.size() >= 4000000) throw TooComplex{}; applyMemo.emplace(key, result); return result; } pair<ld, ld> probabilities(int root) { vector<ld> logValid(nodes.size(), NEG_INF); vector<ld> logInvalid(nodes.size(), NEG_INF); logValid[0] = NEG_INF; logInvalid[0] = 0; logValid[1] = 0; logInvalid[1] = NEG_INF; auto logSumFour = [](const array<ld, 4>& values) { ld maximum = NEG_INF; for (ld x : values) maximum = max(maximum, x); if (maximum == NEG_INF) return NEG_INF; ld sum = 0; for (ld x : values) { if (x != NEG_INF) sum += expl(x - maximum); } return maximum + logl(sum); }; for (int id = 2; id < (int)nodes.size(); ++id) { array<ld, 4> validValues, invalidValues; for (int c = 0; c < 4; ++c) { int child = nodes[id].child[c]; validValues[c] = logValid[child]; invalidValues[c] = logInvalid[child]; } logValid[id] = logSumFour(validValues) - LN2; logInvalid[id] = logSumFour(invalidValues) - LN2; if (logValid[id] > 0 && logValid[id] < 1e-15L) logValid[id] = 0; if (logInvalid[id] > 0 && logInvalid[id] < 1e-15L) { logInvalid[id] = 0; } } return {logValid[root], logInvalid[root]}; } private: vector<BDDNode> nodes; unordered_map<BDDUniqueKey, int, BDDUniqueHash> uniqueNodes; unordered_map<ull, int, U64Hash> applyMemo; int makeNode(int variable, const array<int, 4>& child) { if (child[0] == child[1] && child[1] == child[2] && child[2] == child[3]) { return child[0]; } BDDUniqueKey key; key.first = (ull)(uint32_t)child[0] | ((ull)(uint32_t)child[1] << 32); key.second = (ull)(uint32_t)child[2] | ((ull)(uint32_t)child[3] << 32); key.variable = (uint32_t)variable; auto found = uniqueNodes.find(key); if (found != uniqueNodes.end()) return found->second; if (nodes.size() >= 2500000) throw TooComplex{}; int id = (int)nodes.size(); nodes.push_back({variable, child}); uniqueNodes.emplace(key, id); return id; } }; struct RandomGenerator { ull state; explicit RandomGenerator(ull seed) : state(seed) {} ull next() { state += 0x9e3779b97f4a7c15ULL; return U64Hash::splitmix64(state); } }; static ProbabilityResult estimateComponent( const vector<string>& patterns ) { int m = (int)patterns.size(); int n = (int)patterns[0].size(); vector<vector<int>> fixed(m), wildcard(m); for (int i = 0; i < m; ++i) { for (int position = 0; position < n; ++position) { if (patterns[i][position] == '?') { wildcard[i].push_back(position); } else { fixed[i].push_back(position); } } } PatternTrie trie(n); bool useScan = false; try { for (const string& pattern : patterns) trie.insert(pattern); } catch (const TooComplex&) { trie.nodes.clear(); trie.nodes.shrink_to_fit(); useScan = true; } auto countMatches = [&](const string& value) { if (!useScan) return trie.countMatches(value); int answer = 0; for (int i = 0; i < m; ++i) { bool matches = true; for (int position : fixed[i]) { if (patterns[i][position] != value[position]) { matches = false; break; } } answer += matches; } return answer; }; RandomGenerator rng(0x243f6a8885a308d3ULL); const string alphabet = "ACGT"; vector<ld> sum(m, 0), sumSquares(m, 0); vector<size_t> samples(m, 0); ld probabilityEstimate = 0; auto addSample = [&](int i) { string value = patterns[i]; for (int position : wildcard[i]) { value[position] = alphabet[rng.next() & 3ULL]; } int multiplicity = max(1, countMatches(value)); ld observation = 1.0L / (ld)multiplicity; sum[i] += observation; sumSquares[i] += observation * observation; ++samples[i]; }; vector<int> stochastic; int maximumWildcards = 0; for (int i = 0; i < m; ++i) { maximumWildcards = max(maximumWildcards, (int)wildcard[i].size()); if (wildcard[i].size() <= 3) { int combinations = 1 << (2 * (int)wildcard[i].size()); ld observationSum = 0; for (int code = 0; code < combinations; ++code) { int x = code; string value = patterns[i]; for (int position : wildcard[i]) { value[position] = alphabet[x & 3]; x >>= 2; } int multiplicity = max(1, countMatches(value)); observationSum += 1.0L / (ld)multiplicity; } ld mean = observationSum / combinations; ld scale = exp2l(2.0L * ((ld)wildcard[i].size() - n)); probabilityEstimate += scale * mean; } else { stochastic.push_back(i); } } if (!stochastic.empty()) { vector<ld> weight(m, 0); ld totalWeight = 0; for (int i : stochastic) { weight[i] = exp2l(2.0L * ((ld)wildcard[i].size() - maximumWildcards)); totalWeight += weight[i]; } sort(stochastic.begin(), stochastic.end(), [&](int a, int b) { return weight[a] > weight[b]; }); size_t budget = (size_t)max( 20000ULL, min(1000000ULL, 50000000ULL / (size_t)(n + 1)) ); budget = max(budget, min((size_t)m, 1000000ULL)); size_t selected = min(budget, stochastic.size()); vector<int> chosen(stochastic.begin(), stochastic.begin() + selected); for (int i : chosen) samples[i] = 1; size_t remaining = budget - selected; if (remaining && totalWeight > 0) { vector<size_t> additions(selected, 0); size_t distributed = 0; for (size_t j = 0; j < selected; ++j) { size_t addition = (size_t)( (ld)remaining * weight[chosen[j]] / totalWeight ); additions[j] = addition; distributed += addition; } for (size_t j = 0; distributed < remaining; ++j) { ++additions[j]; ++distributed; } for (size_t j = 0; j < selected; ++j) { samples[chosen[j]] += additions[j]; } } for (int i : chosen) { for (size_t k = 0; k < samples[i]; ++k) addSample(i); } for (int i : chosen) { if (!samples[i]) continue; ld mean = sum[i] / (ld)samples[i]; ld scale = exp2l(2.0L * ((ld)wildcard[i].size() - n)); probabilityEstimate += scale * mean; } auto sampleVariance = [&](int i) { if (samples[i] <= 1) return 0.0L; ld value = (sumSquares[i] - sum[i] * sum[i] / (ld)samples[i]) / (ld)(samples[i] - 1); return max(0.0L, value); }; size_t extraBudget = budget; for (int round = 0; round < 3 && extraBudget; ++round) { ld totalErrorSquared = 0; vector<pair<ld, int>> errors; for (int i : chosen) { if (!samples[i]) continue; ld variance = sampleVariance(i); ld scale = exp2l(2.0L * ((ld)wildcard[i].size() - n)); ld error = scale * sqrtl(variance / (ld)samples[i]); totalErrorSquared += error * error; errors.push_back({error, i}); } ld totalError = sqrtl(totalErrorSquared); if (probabilityEstimate <= 0 || totalError <= 0.005L * probabilityEstimate) { break; } sort(errors.begin(), errors.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); for (const auto& entry : errors) { if (!extraBudget) break; if (entry.first <= 0) continue; size_t addition = min( extraBudget, max<size_t>(8, samples[entry.second]) ); for (size_t k = 0; k < addition; ++k) addSample(entry.second); samples[entry.second] += addition; extraBudget -= addition; } } for (int i : chosen) { if (!samples[i]) continue; ld mean = sum[i] / (ld)samples[i]; ld scale = exp2l(2.0L * ((ld)wildcard[i].size() - n)); probabilityEstimate += scale * mean; } } probabilityEstimate = min(1.0L, max(0.0L, probabilityEstimate)); ProbabilityResult result; if (probabilityEstimate <= 0) { result.logValid = NEG_INF; result.logInvalid = 0; } else { result.logValid = logl(probabilityEstimate); if (probabilityEstimate >= 1) { result.logInvalid = NEG_INF; } else { result.logInvalid = log1pl(-probabilityEstimate); } } return result; } static ProbabilityResult solveComponent(const vector<string>& patterns) { int m = (int)patterns.size(); int n = (int)patterns[0].size(); bool allFixed = true; for (const string& pattern : patterns) { int fixed = 0; for (char c : pattern) fixed += (c != '?'); if (fixed != n) { allFixed = false; break; } } if (allFixed) { ld logValid = logl((ld)m) - 2.0L * n * LN2; if (m == (1LL << (2 * min(n, 31)))) logValid = 0; return probabilityFromLogValid(logValid); } if (m == 1) { int fixed = 0; for (char c : patterns[0]) fixed += (c != '?'); return probabilityFromLogValid(-2.0L * fixed * LN2); } if (m <= 24) { return exactInclusionExclusion(patterns); } ProbabilityResult smallResult; if (exactSmallComponent(patterns, smallResult)) return smallResult; long long estimatedWork = 1LL * n * m; if (n <= 1500 && m <= 100000 && estimatedWork <= 4000000) { try { vector<int> order(m); iota(order.begin(), order.end(), 0); sort(order.begin(), order.end(), [&](int a, int b) { int ca = 0, cb = 0; for (char c : patterns[a]) ca += (c != '?'); for (char c : patterns[b]) cb += (c != '?'); return ca > cb; }); BDD bdd; int root = 0; for (int index : order) { int pattern = bdd.buildPattern(patterns[index]); root = bdd.unite(root, pattern); if (root == 1) break; } auto [logValid, logInvalid] = bdd.probabilities(root); ProbabilityResult result; result.logValid = logValid; result.logInvalid = logInvalid; if (result.logInvalid == 0 && logValid < -30) { result = probabilityFromLogValid(logValid); } return result; } catch (const TooComplex&) { } } return estimateComponent(patterns); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m; cin >> n >> m; vector<string> input(m); for (string& s : input) cin >> s; sort(input.begin(), input.end()); input.erase(unique(input.begin(), input.end()), input.end()); vector<Pattern> patterns; patterns.reserve(input.size()); bool coversEverything = false; bool allConcrete = true; for (string& s : input) { Pattern pattern; pattern.s = move(s); for (int position = 0; position < n; ++position) { if (pattern.s[position] == '?') { coversEverything = true; } else { pattern.fixedPositions.push_back(position); } } if ((int)pattern.fixedPositions.size() != n) allConcrete = false; patterns.push_back(move(pattern)); } if (coversEverything) { printProbability(0); return 0; } if (allConcrete) { ld logProbability = logl((ld)patterns.size()) - 2.0L * n * LN2; printProbability(logProbability); return 0; } patterns = removeRedundantPatterns(move(patterns)); DSU dsu(n); for (const Pattern& pattern : patterns) { int first = pattern.fixedPositions.front(); for (int position : pattern.fixedPositions) { dsu.unite(first, position); } } unordered_map<int, vector<int>> componentPatterns; for (int i = 0; i < (int)patterns.size(); ++i) { int root = dsu.find(patterns[i].fixedPositions.front()); componentPatterns[root].push_back(i); } vector<ProbabilityResult> results; results.reserve(componentPatterns.size()); for (const auto& entry : componentPatterns) { const vector<int>& ids = entry.second; vector<int> positions; for (int id : ids) { positions.insert(positions.end(), patterns[id].fixedPositions.begin(), patterns[id].fixedPositions.end()); } sort(positions.begin(), positions.end()); positions.erase(unique(positions.begin(), positions.end()), positions.end()); vector<string> localPatterns; localPatterns.reserve(ids.size()); for (int id : ids) { string local; local.reserve(positions.size()); for (int position : positions) local.push_back(patterns[id].s[position]); localPatterns.push_back(move(local)); } results.push_back(solveComponent(localPatterns)); } ld globalLogValid; if (results.size() == 1) { globalLogValid = results[0].logValid; } else { ld sumLogInvalid = 0; bool invalidZero = false; vector<ld> logValidValues; logValidValues.reserve(results.size()); for (const ProbabilityResult& result : results) { logValidValues.push_back(result.logValid); if (result.logInvalid == NEG_INF) { invalidZero = true; break; } sumLogInvalid += result.logInvalid; } if (invalidZero) { globalLogValid = 0; } else { ld globalValid = -expm1l(sumLogInvalid); if (globalValid <= 0) { globalLogValid = logSumExp(logValidValues); } else { globalLogValid = logl(globalValid); } } } printProbability(globalLogValid); return 0; }