摸鱼过法,多谢楼上老大哥的解答
2进制状态表达
利用哈希表存储当前已经到达的状态记忆化搜索, 内存什么的就不管了(╯‵□′)╯︵┻━┻(绕过不会的dp想法)
#include <iostream>
#include <unordered_set>
#include <unordered_map>
using namespace std;
const int N = 110, K = 22;
int pa[N];
int n, m, k;
int ans = -1;
unordered_map<int, int> dps;
void dfs(int tp, int status, int ns, unordered_map<int, unordered_set<int>>& ms)
{
// cout<<"tp is "<<tp<<endl;
if(dps.count(status) && dps[status] <= ns)return;
dps[status] = ns;
while(tp <= m && ((status >> tp) & 1))++tp;
if(tp == m + 1)
{
// cout<<"status "<<status<<endl;
if(ans < 0 || ns < ans)ans = ns;
return;
}
{
// cout<<"else situation!"<<endl;
for(auto ni:ms[tp])
{
// cout<<"ni is "<<ni<<endl;
dfs(tp+1, status|pa[ni], ns+1, ms);
}
}
}
int main()
{
cin>>n>>m>>k;
unordered_map<int, unordered_set<int>> ms;
int cs = 0;
for(int i = 1; i <= n; ++i)
{
int t;
for(int j = 0; j < k; ++j)
{
cin>>t;
pa[i] = pa[i] | (1<<t);
ms[t].insert(i);
}
cs |= pa[i];
// cout<<hex<<pa[i]<<endl;
}
if(cs != (1 << (m+1)) - 2)cout<<"-1"<<endl;
else
{
dfs(1, 0, 0, ms);
cout<<ans<<endl;
}
return 0;
}