解題思路
計算符合全部A、B猜測的互異數字秘密組合。
猜測以左補0還原n位。A+B只決定猜測數字集合與秘密集合的交集大小,因此先枚舉至多C(10,n)個秘密數字集合,排除總匹配數不符者。
對每個剩餘集合由左到右放尚未使用數字;維護每個猜測的已確定A數,若超標,或所有剩餘可能相同位置都不足所需A,就剪枝。
所有完整排列恰對應一個秘密組合;集合交集已保證A+B,位置A相同即B也相同。重複猜測可去重,矛盾猜測立即無解。只有一條位置約束時以位元遮罩DP加速計數。
Python額外把0A線索壓成每個位置的禁用數字;若只剩這類限制,以已用數字位元集合做DP,避免完整列舉所有錯排。
最壞時間 O(U n²×10!/(10−n)!+mn),空間 O(Un+n),U為去重猜測數;單約束用O(n2^n) DP。大量互異線索的最壞搜尋成本高,不能保證所有原上限組合都於2秒內完成。
Step-by-step animation
數字集合過濾與位置約束回溯逐步追蹤
步驟 1 / 3
步驟 1
首範例12、34、56皆0A0B,排除數字1至6。
可用0,7,8,9
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n, m;
cin >> n >> m;
map<string, pair<int, int>> mapc;
map<int, int> tot;
bool bad = false;
for (int i = 0; i < m; i++) {
string s;
int A, B;
cin >> s >> A >> B;
s = string(max(0, n - (int)s.size()), '0') + s;
int mask = 0;
for (char c : s)
mask |= 1 << (c - '0');
if (mapc.count(s) && mapc[s] != make_pair(A, B))
bad = true;
mapc[s] = {A, B};
if (tot.count(mask) && tot[mask] != A + B)
bad = true;
tot[mask] = A + B;
}
if (bad) {
cout << 0 << '\n';
return 0;
}
vector<string> guess;
vector<int> want;
for (auto [s, v] : mapc) {
guess.push_back(s);
want.push_back(v.first);
}
int U = guess.size();
ll answer = 0;
for (int mask = 0; mask < 1024; mask++)
if (__builtin_popcount((unsigned)mask) == n) {
bool ok = true;
for (auto [cm, k] : tot)
if (__builtin_popcount((unsigned)(mask & cm)) != k) {
ok = false;
break;
}
if (!ok)
continue;
if (U == 1) {
map<pair<int, int>, ll> memo;
function<ll(int, int)> go = [&](int used, int hits) {
int pos = __builtin_popcount((unsigned)used);
if (hits > want[0] || hits + n - pos < want[0])
return 0LL;
if (pos == n)
return (ll)(hits == want[0]);
auto key = make_pair(used, hits);
if (memo.count(key))
return memo[key];
ll sum = 0;
for (int d = 0; d < 10; d++)
if ((mask >> d & 1) && !(used >> d & 1))
sum +=
go(used | (1 << d), hits + (guess[0][pos] - '0' == d));
return memo[key] = sum;
};
answer += go(0, 0);
continue;
}
vector<int> hits(U);
function<void(int, int)> dfs = [&](int pos, int used) {
if (pos == n) {
answer++;
return;
}
for (int d = 0; d < 10; d++)
if ((mask >> d & 1) && !(used >> d & 1)) {
int nu = used | (1 << d);
bool good = true;
for (int c = 0; c < U; c++) {
int now = hits[c] + (guess[c][pos] - '0' == d),
possible = 0;
for (int j = pos + 1; j < n; j++) {
int q = guess[c][j] - '0';
if ((mask >> q & 1) && !(nu >> q & 1))
possible++;
}
if (now > want[c] || now + possible < want[c]) {
good = false;
break;
}
}
if (!good)
continue;
for (int c = 0; c < U; c++)
hits[c] += guess[c][pos] - '0' == d;
dfs(pos + 1, nu);
for (int c = 0; c < U; c++)
hits[c] -= guess[c][pos] - '0' == d;
}
};
dfs(0, 0);
}
cout << answer << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。