题目
思路
看到 S ≤ 30 S\le 30 S≤30 ,你有什么想法?没错,折半搜索。 m e e t - i n - m i d d l e \tt meet\text{-}in\text{-}middle meet-in-middle 中途相遇。
假如以 m m m 为界限那么复杂度是 O ( n 2 m m + n m d 2 S − m ) \mathcal O(n2^{m}m+nmd2^{S-m}) O(n2mm+nmd2S−m) 。如果粗略的认为 m = log n m=\log n m=logn 那么复杂度就是 O ( n d 2 S log n ) \mathcal O(n\sqrt{d2^{S}}\log n) O(nd2Slogn) 。
然而这不足以让我们通过本题。于是想到 b i t s e t \tt bitset bitset 优化。然后就过掉了???
看一眼题解,发现就是这样。唯一的不同是用
h
a
s
h
m
a
p
hashmap
hashmap 去掉那个
log
\log
log 。这样真的好吗。
代码
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
typedef long long int_;
inline int readint(){
int a = 0; char c = getchar(), f = 1;
for(; c<'0'||c>'9'; c=getchar())
if(c == '-') f = -f;
for(; '0'<=c&&c<='9'; c=getchar())
a = (a<<3)+(a<<1)+(c^48);
return a*f;
}
const int MaxN = 1005;
const int Mod1 = 998244353;
const int Mod2 = 1e9+7;
struct PAIR{
int a[2];
bool operator < (const PAIR &t) const {
return (a[0]^t.a[0]) ?
a[0] < t.a[0] : a[1] < t.a[1];
}
};
struct BitSet{
unsigned long long a[16];
// len1 = 2^{64} % Mod1
static const int len1 =
(-1ull)%Mod1+1;
static const int len2 =
(-1ull)%Mod2+1;
BitSet(){ memset(a,0,128ull); }
inline void set(int p){
a[p/64] |= (1ull<<(p%64));
}
inline void operator ^= (const BitSet &t){
for(int i=0; i<16; ++i)
a[i] ^= t.a[i];
}
inline PAIR hashVal() const {
PAIR res; res.a[0] = res.a[1] = 0;
for(int i=15; ~i; --i){
res.a[0] = (res.a[0]*1ull*len1+a[i])%Mod1;
res.a[1] = (1ull*res.a[1]*len2+a[i])%Mod2;
}
return res;
}
};
BitSet c[31]; // 每个机器人的能力
int n, s, m; // basic information
map< PAIR,int > mp; // 2^{20} 中查
BitSet mj[1<<20]; // 枚举出的总效果
int cnt[1<<20]; // __builtin_popcount
void prepare(){
m = min(s,20);
for(int i=0; i<m; ++i){
mj[1<<i] = c[i];
cnt[1<<i] = 1; // 预处理
}
for(int S=1; S<(1<<m); ++S){
if(S == (S&-S)) continue;
cnt[S] = cnt[S-(S&-S)]+1;
mj[S] = mj[S-(S&-S)];
mj[S] ^= mj[S&-S];
}
for(int i=(1<<m)-1; ~i; --i){
int &x = mp[mj[i].hashVal()];
// printf("mj[%d] = %d\n",i,mj[i].hashVal());
if(!x || x > cnt[i])
x = cnt[i]; // 求最小操作
}
for(int i=0; i<s-m; ++i)
mj[1<<i] = c[i+m];
for(int S=1; S<(1<<(s-m)); ++S)
if(S != (S&-S)){
mj[S] = mj[S-(S&-S)];
mj[S] ^= mj[S&(-S)];
}
}
BitSet want; // 需要解决的问题
void solve(){
BitSet now; // 临时使用
int ans = MaxN; // 其实最大 s
for(int i=0; i<(1<<(s-m)); ++i){
if(cnt[i] >= ans) continue;
now = want; now ^= mj[i];
PAIR x = now.hashVal();
if(mp.count(x)) // 可以做到
ans = min(ans,cnt[i]+mp[x]);
}
if(ans == MaxN) ans = -1;
printf("%d\n",ans);
}
int main(){
n = readint(), s = readint();
int T = readint(); // 询问组数
for(int i=0; i<s; ++i){
int t = readint();
while(t --) // 读入
c[i].set(readint()-1);
}
prepare(); // 记得要做
while(T --){
want = BitSet(); // clear
int t = readint();
while(t --) // 方式同上
want.set(readint()-1);
solve(); // 直接输出
}
return 0;
}