Button Lock
Tx_Lcy
·
·
题解
题目传送门
思路
考虑二分图最大匹配。
我们先建图:$s_i$ 和 $s_j$ 之间有边当且仅当 $s_i$ 是 $s_j$ 的子集。
这显然是个 $\rm DAG$,那么问题转化成:选择若干条路径覆盖此 $\rm DAG$ 的所有点,每条路径的权值是结尾节点的 $\rm popcnt+1$,要求权值最小。
然后我们发现,出现 $s_i$ 这个状态后,我们需要选择一个 $j$,满足 $i,j$ 有边,然后把状态 $s_i$ 改成状态 $s_j$,这样的 $j$ 只能选一个。
这个条件相当于 $i$ 可以跟与 $i$ 有边的 $j$ 中的一个匹配。
如果说 $i$ 没有匹配上,$i$ 就是某条路径的终点。
最优解肯定是拆点二分图最大匹配中的一个,这是显然的,因为如果还能匹配,那么答案一定还能减少。
现在有权值的条件,我们按照权值从大到小排序,然后按照这个顺序进行二分图最大匹配即可。
输出方案可以从每条路径的终点开始暴力跳匹配。
最坏情况图中有 $2^d$ 个点,$3^d$ 条边,时间复杂度 $\mathcal O(6^d)$。
## 代码
```cpp
//A tree without skin will surely die.
//A man without face is invincible.
#include<bits/stdc++.h>
using namespace std;
int const N=1e4+10;
int a[N],g[N],matched[N],vis[N],id[N];
vector<int>b[N];
bool Hungary(int x,int co){
for (auto v:b[x]){
if (vis[v]==co) continue;
vis[v]=co;
if (!matched[v] || Hungary(matched[v],co))
return matched[v]=x,1;
}
return 0;
}
void solve(){
int n,k;cin>>n>>k;
for (int i=1;i<=k;++i){
string s;cin>>s;
for (int j=0;j<n;++j)
if (s[j]=='1') a[i]+=1<<j,++g[i];
}
for (int i=1;i<=k;++i)
for (int j=1;j<=k;++j)
if (i!=j && (a[i]&a[j])==a[i]) b[i].push_back(j);
for (int i=1;i<=k;++i)
sort(b[i].begin(),b[i].end(),[&](int x,int y){return g[x]>g[y];});
int ans=-1,idx=0;
vector<int>res;
for (int i=1;i<=k;++i) id[i]=i;
sort(id+1,id+k+1,[&](int x,int y){return g[x]>g[y];});
for (int i=1;i<=k;++i)
if (!Hungary(id[i],++idx)) res.push_back(id[i]),ans+=g[id[i]]+1;
cout<<ans<<'\n';
for (auto i:res){
int x=i;vector<int>g;
while (x) g.push_back(a[x]),x=matched[x];
reverse(g.begin(),g.end());
int la=0;
for (auto i:g){
for (int k=0;k<n;++k)
if ((la^i)>>k&1) cout<<k<<' ',--ans;
la=i;
}
if (ans) cout<<"R ",--ans;
}
cout<<'\n';
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int t=1;
// cin>>t;
while (t--) solve();
cerr<<"Running Time: "<<(double)clock()/CLOCKS_PER_SEC<<" s\n";
return 0;
}
```