好题!于是写一篇题解记录一下。
乍一看无论怎么做时间复杂度都是 O(22n) 的,于是我们考虑按位处理。
遇事不决,先推式子
这里我们钦定读者已经掌握了艾弗森括号。
我们约定大写字母表示集合,小写字母表示其对应的二进制表示。约定映射 f(S)=s,f−1(s)=S。
先指出两个显然的定理:
- 若有 a∈f−1(s),则 a+1∈f−1(s×2)。
此处的 s×2 即 s 右移一位。
- 若有 S∈f−1(a),S∈f−1(b),则 S∈f−1(a∧b)。
对于某个已经在开头 n 位合法的 s,现在考察其第 n−1 位的情况,考察:
∀t∈[0,2n−1),∣S∩f−1(t)∣∈?f−1(vt)
∀t∈[0,2n−1),∣S∩f−1(t+2n−1)∣∈?f−1(vt+2n−1)
对于下面一种情况,显然有:
∀t∈[0,2n−1),∣S∩f−1(t)∣+[n−1∈S]∈?f−1(vt+2n−1)
分讨 n−1∈S 的情况。
若 n−1∈S,上式结合最初我们提到的定理一可得:
∀t∈[0,2n−1),∣S∩f−1(t)∣∈?f−1(vt+2n−1×2)
再把之前的第一式也放过来:
∀t∈[0,2n−1),⎩⎨⎧∣S∩f−1(t)∣∈?f−1(vt)∣S∩f−1(t)∣∈?f−1(vt+2n−1×2)
利用定理二合并:
∀t∈[0,2n−1),∣S∩f−1(t)∣∈?f−1(vt∧(vt+2n−1×2))
另一种情况的讨论同理,读者自推不难,这里只放出结果。
- 当 n−1∈S 时:∀t∈[0,2n−1),∣S∩f−1(t)∣∈?f−1(vt∧(vt+2n−1×2))
- 当 n−1∈/S 时:∀t∈[0,2n−1),∣S∩f−1(t)∣∈?f−1(vt∧vt+2n−1)
推到这里,我们发现不妨先后钦定 S 的第 n−1 位为 0 和 1,然后进行递归,这样每次区间就会由 [0,2n) 缩到 [0,2n−1),这样一共进行 log(n) 次量级的递推,每次会完整地将整个限制合并一遍共 n 次,总时间复杂度为 O(nlogn)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include <iostream> #include <cstdio> #include <cctype> #include <vector> using namespace std; inline void read(int &x) { char c=getchar();x=0; while(!isdigit(c)) c=getchar(); while(isdigit(c)) x=x*10+c-48,c=getchar(); } vector<int> V,ans; void dfs(int s,vector<int> v,int l) { if(l==0) { if(v[0]&1) ans.push_back(s); return; } int n=1<<l; vector<int> sub; for(int i=0;i<n>>1;i++) sub.push_back(v[i]&v[i+(n>>1)]); dfs(s,sub,l-1);sub.clear(); for(int i=0;i<n>>1;i++) sub.push_back(v[i]&(v[i+(n>>1)]>>1)); dfs(s|(1<<l>>1),sub,l-1); } int main() { int n=0,l=0; read(l);n=1<<l; for(int i=1,u;i<n;i++) read(u),V.push_back(u); V.insert(V.begin(),1); dfs(0,V,l); printf("%d\n",ans.size()); for(int i:ans) printf("%d\n",i); return 0; }
|