解題思路
用 n 位遮罩表示可靠者集合。對每位線人 x,預先建立正證詞 pos[x] 與負證詞 neg[x] 的遮罩。若 x 被選入,必須同時滿足 pos[x] 完全包含於集合、neg[x] 與集合沒有交集;未被選入的人不限制他的證詞。
枚舉全部 2ⁿ 個集合,每個集合只檢查已選的人。任一證詞衝突立即淘汰;通過的集合更新最大位元數。可以跳過人數不可能改善答案的集合。自稱不可靠會使該人無法入選,但不會使整筆資料無解,空集合永遠合法。0 0 結束。
Step-by-step animation
示意:三人,1 說 2 可靠,2 說 3 不可靠
步驟 1 / 3
選集合 {1}
1 要求 2 入選,目前沒有,集合不合法。
mask=001
pos[1]=010
- 人數
- 1
- 合法
- 0
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
int main() {
int n, a;
while (cin >> n >> a && (n || a)) {
vector<int> pos(n), neg(n);
while (a--) {
int x, y;
cin >> x >> y;
--x;
if (y > 0)
pos[x] |= 1 << (y - 1);
else
neg[x] |= 1 << (-y - 1);
}
int ans = 0;
for (int mask = 0; mask < (1 << n); ++mask) {
int count = 0;
for (int v = mask; v; v &= v - 1)
++count;
if (count <= ans)
continue;
bool ok = true;
for (int i = 0; i < n && ok; ++i)
if (mask & (1 << i))
if ((mask & pos[i]) != pos[i] || (mask & neg[i]))
ok = false;
if (ok)
ans = count;
}
cout << ans << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。