浅谈搜索状压
1.简介
搜索状压,就是字面意思:搜索(dfs or bfs 都可以) + 状态压缩(有可能需要dp)。
那么,我们什么时候需要它呢?
很显然,在面对01dfs(暴力选或不选),01bfs(纯广搜)的优化时,可以用上它。
2.例题:P8687 [蓝桥杯 2019 省 A] 糖果
题目大意:
给定
思路:
可以先把每包糖果有哪些糖果用二进制,然后暴力dfs去看这包糖果选或不选,最后找到买的包数最少的那种情况即可。
代码:
#include <bits/stdc++.h>
using namespace std ;
int n , m , k , tmp[105] , f[105] , ans = 0x3f3f3f3f ;
void dfs(int stadus , int step)
{
if(stadus == (1 << m) - 1)
{
int cnt = 0 ;
for(int i = 1 ; i <= n ; i ++) if(f[i]) cnt ++ ;
ans = min(ans , cnt) ;
return ;
}
if(step == n) return ;
f[step] = 1 ;
dfs(stadus | tmp[step] , step + 1) ;
f[step] = 0 ;
dfs(stadus , step + 1) ;
}
int main()
{
ios::sync_with_stdio(0) ;
cin.tie(0) ;
cin >> n >> m >> k ;
for(int i = 1 ; i <= n ; i ++)
{
for(int j = 1 ; j <= k ; j ++)
{
int x ;
cin >> x ;
tmp[i] = tmp[i] | (1 << x - 1) ;
}
}
dfs(0 , 1) ;
if(ans == 0x3f3f3f3f) cout << -1 ;
else cout << ans ;
return 0 ;
}