b_lq_糖果(预处理糖果的贡献)

给定 N 包糖果(一包K个,有M种口味),请你计算小明最少买几包,就可以品尝到所有口味的糖果。

思路
对于每一袋糖果,我都可以要或不要:

  • 要的话,需满足:f[nx]==-1 || f[nx]>f[i]+1;(nx=i|ST[j],nx是选完第j包糖果后的状态,i是原状态,ST[j]是第j包糖果的贡献,j∈[0,n))
  • 不要可以直接省略
#include<bits/stdc++.h>
using namespace std;
int main() {
    std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    int n,m,k; cin>>n>>m>>k;    //n包糖果,m种口味,每包k颗
    int tot=1<<m, a[n], f[tot+5];
    fill(f, f+tot+5, -1); f[0]=0;
    
    for (int i=0; i<n; i++) {
        int st=0;
        for (int j=0; j<k; j++) {
            int x; cin>>x;
            st|=(1<<(x-1));
        }
        a[i]=st, f[st]=1;
    }
    for (int i=0; i<tot; i++) if (f[i]!=-1)
    for (int j=0; j<n; j++) {
        int st=a[j]; 
        if (f[i|st]==-1 || f[i|st]>f[i]+1) //i|st 是新状态
            f[i|st]=f[i]+1;            
    }
    cout<<f[tot-1];
    return 0;
}
原文地址:https://www.cnblogs.com/wdt1/p/13778503.html