UVA 10118 Free Candies

本文通过记忆化搜索的方法解决了一个看似简单的数塔问题,深入探讨了动态规划的运用和算法优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//开始以为是个数塔。。。

//记忆化搜索:dp[a][b][c][d]的意义是第一堆选了a, 第二堆选了b个, 。。。。。之后剩下的最大值;

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 40 + 5;
int vis[maxn][4];
int dp[maxn][maxn][maxn][maxn];
int n;
int solve(int a, int b, int c, int d, int s, int res)
{
    if(a==n && b==n && c==n && d==n || res == 5) return dp[a][b][c][d] = 0;
    if(dp[a][b][c][d] != -1) return dp[a][b][c][d];
    int ans = 0;
    if(a != n)
    {
        int p = (1<<vis[a+1][0]);
        if(s&p)
            ans = max(ans, solve(a+1, b, c, d, s ^ p, res -1)+1);
        else ans = max(ans,solve(a+1, b, c, d, s + p, res +1));
    }
    if(b != n)
    {
        int p = (1<<vis[b+1][1]);
        if(s&p)
            ans = max(ans, solve(a, b+1, c, d, s ^ p, res -1)+1);
        else ans = max(ans,solve(a, b+1, c, d, s + p, res +1));
    }
    if(c != n)
    {
        int p = (1<<vis[c+1][2]);
        if(s&p)
            ans = max(ans, solve(a, b, c+1, d, s ^ p, res -1)+1);
        else ans = max(ans,solve(a, b, c+1, d, s + p, res +1));
    }
    if(d != n)
    {
        int p = (1<<vis[d+1][3]);
        if(s&p)
            ans = max(ans, solve(a, b, c, d+1, s ^ p, res -1)+1);
        else ans = max(ans,solve(a, b, c, d+1, s + p, res +1));
    }
    return dp[a][b][c][d] = ans;
}
int main()
{
    while(scanf("%d", &n) == 1 && n)
    {
        memset(vis,0,sizeof(vis));
        memset(dp,-1,sizeof(dp));
        for(int i = 1; i <= n; ++i)
            for(int j = 0; j < 4; ++j) scanf("%d", &vis[i][j]);
        printf("%d\n",solve(0,0,0,0,0,0));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值