UVA 10118 简单DP

题意

四堆糖果,有一个容量为5的篮子,每次可以从糖果堆顶端取一个糖果,若篮子中恰好有相同颜色的糖果,则将该糖果装入口袋中。问最多可以取多少个糖果。

题解

设dp[i][j][k][m]为四堆分别取了i,j,k,m个后,最多还能取多少个糖果。使用hash标记篮子中有的糖果颜色,DFS记忆化搜索即可得解。

代码

#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>

using namespace std;
int mp[50][5];
int dp[50][50][50][50];
int top[50];
int n;

int dfs(int count,bool hash[]){
    if(dp[top[0]][top[1]][top[2]][top[3]]!=-1){
        return dp[top[0]][top[1]][top[2]][top[3]];
    }
    if(count==5)
        return dp[top[0]][top[1]][top[2]][top[3]]=0;
    int ans=0;
    for(int i=0;i<4;i++){
        if(top[i]==n)
            continue;
        int color=mp[top[i]][i];
        top[i]+=1;
        if(hash[color]){
            hash[color]=false;
            ans=max(ans,dfs(count-1,hash)+1);
            hash[color]=true;
        }else{
            hash[color]=true;
            ans=max(ans,dfs(count+1,hash));
            hash[color]=false;
        }
        top[i]-=1;
    }
    return dp[top[0]][top[1]][top[2]][top[3]]=ans;
}

int main()
{
    while(scanf("%d",&n)!=EOF){
        if(n==0)
            break;
        for(int i=0;i<n;i++){
            for(int j=0;j<4;j++){
                scanf("%d",&mp[i][j]);
            }
        }
        memset(dp,-1,sizeof(dp));
        memset(top,0,sizeof(top));
        bool hash[30];
        memset(hash,false,sizeof(hash));
        printf("%d\n",dfs(0,hash));
    }
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值