题目很straightforward的, 看到n范围很小考虑状压, 暴力枚举所有的可能pattern.
第一种做法, 暴力枚举是\(O(2^n)\)的, 然后check函数判断是\(O(n^2)\)的, 一共是\(O(n^22^n)\)的, 可以通过.
第二种做法, 我们考虑把判断pattern是否合法的限制条件也压成二进制串, 那么我们比对条件就变成\(O(1)\), check函数判断变成
\(O(n)\), 总时间复杂度降为\(O(n2^n)\)
AC代码:
/*
Author: SJ
*/
#include<bits/stdc++.h>
const int N = 1e5 + 10;
using ll = long long;
using ull = unsigned long long;
using namespace std;
int n;
vector<int> a, b, s;
bool check(int x) {
for (int i = 0; i < n; i++) {
if (s[i] && (x & (1 << i)) && ((s[i] & x) == s[i])) {
return false;
}
}
return true;
}
ll query(int x) {
ll res = 0;
for (int i = 0; i < n; i++) {
if (x & (1 << i)) {
res += a[i];
}
}
return res;
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
//freopen("data.in", "r", stdin);
//freopen("data.ans", "w", stdout);
cin >> n;
a.assign(n, 0);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
b.assign(n, 0);
s.assign(n, 0);
for (int i = 0; i < n; i++) {
cin >> b[i];
for (int j = 0; j < b[i]; j++) {
int x;
cin >> x;
x--;
s[i] |= (1 << x);
}
}
ll ans = -1;
for (int i = 0; i < (1 << n); i++) {
if (check(i)) {
ans = max(ans, (ll)query(i));
}
}
cout << ans;
return 0;
}
标签:int,状压,枚举,long,++,daimayuan252,check
From: https://www.cnblogs.com/IhopeIdieyoung/p/17641774.html