uva10118

题目大意:
有4堆糖果,每堆有n(最多40)个,有一个篮子,最多装5个糖果,我们每次只能从某一堆糖果里拿出一个糖果,

如果篮子里有两个相同的糖果,那么就可以把这两个(一对)糖果放进自己的口袋里,问最多能拿走多少对糖果。糖果种类最多20种.

思路:
记忆化搜索
用一个h数组来记录在此之前是否有一个单独的糖果i,如果有h数组中的此位置就变成0,如果没有就为1。然后不断的搜索。知道篮子中有5个糖果或者循环结束。
top[i]表示第i堆的选择到了第几个
dp[top[0]][top[1]][top[2]][top[3]]表示1 2 3 4 堆分别选到了哪一个时候最多的对数。
代码:

#include <iostream>
using namespace std;
#include <stdio.h>
#include <cstring>
const int N = 45;
const int C = 22;
int pile[4][N],dp[N][N][N][N],n,top[4];
int dfs(int s,int hash[C]) {
    if(dp[top[0]][top[1]][top[2]][top[3]] != -1)
        return dp[top[0]][top[1]][top[2]][top[3]];
    if(s == 5)
        return dp[top[0]][top[1]][top[2]][top[3]] = 0;
    int h[C];
    int ans = 0;
    for(int i = 0; i < 4; i++) {
        memcpy(h,hash,sizeof(h));
        if(top[i]!=n) {
            if(h[pile[i][top[i]]]) {
                h[pile[i][top[i]]] = 0;
                top[i]++;
                ans = max(ans,dfs(s - 1,h) + 1);
            }
            else {
                h[pile[i][top[i]]] = 1;
                top[i]++;
                ans = max(ans,dfs(s + 1,h));
            }
            top[i]--;//回溯
        }
    }
    return dp[top[0]][top[1]][top[2]][top[3]] = ans;
}
int main() {
    while(scanf("%d",&n) &&n) {
        memset(pile,0,sizeof(pile));
        for(int i = 0; i < n; i++) 
            for(int j = 0; j < 4; j++)
                scanf("%d",&pile[j][i]);
        memset(dp,-1,sizeof(dp));
        memset(top,0,sizeof(top));
        int hash[C] ={0};
        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、付费专栏及课程。

余额充值