糖果 (蓝桥杯)

题目:https://www.acwing.com/problem/content/description/1245/

  1. dfs+剪枝
    预处理每一列的可选状态, 选择需要被覆盖的列中的最小的分支
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int N=105, M=21;
int log2[1<<M];
vector<int> col[M];
int n,m,k;

int lowbit(int x){
    return x&-x;
}

bool dfs(int depth ,int state){
    if(depth==0) return state==(1<<m)-1;
    
    int t=-1;
    for(int i=(1<<m)-1-state; i; i-=lowbit(i)){
        int c=log2[lowbit(i)];
        if(t==-1||col[c].size()<col[t].size())
            t=c;
    }
    
    for(auto row: col[t])
        if(dfs(depth-1, state|row)) return true;

    return false;
}

int main(){
    cin>>n>>m>>k;
    for(int i=0; i<m; i++) log2[1<<i]=i;
    
    for(int i=0; i<n; i++){
        int state=0;
        int x;
        for(int j=0; j<k; j++){
            cin>>x;
            state|=1<<x-1;
        }
         for(int j=0; j<m; j++){
             if(state>>j&1) col[j].push_back(state);
         }
    }
    
    int depth=0;
    while(depth<=m&&!dfs(depth, 0)) depth++;
    if(depth>m) depth=-1;
    cout<<depth;
    return 0;
}
  1. 状压dp
    先枚举路径,再枚举状态; 每个状态都尝试这条路径
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;

const int M=21, N=105;
int dp[1<<M];
int candy[N][M];
int n,m,k;

int main(){
    cin>>n>>m>>k;
    for(int i=1; i<=n; i++)
        for(int j=1; j<=k; j++) 
           cin>>candy[i][j];
            
    memset(dp, -1, sizeof dp);
    
    int lim=1<<m;
    dp[0]=0;
    for(int i=1; i<=n; i++){
        int t=0;
        for(int j=1; j<=k ;j++) t|=1<<candy[i][j]-1;  //路径t
        int nt;
        for(int st=0; st<lim; st++){
            if(dp[st]==-1) continue;
            int nst=st|t;
            if(dp[nst]==-1||dp[nst]>dp[st]+1) dp[nst]=dp[st]+1; 
        }
    }
    
    cout<<dp[lim-1];
}

参考y总和https://www.acwing.com/user/myspace/index/43062/


  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值