UVa 10118 Free Candies (记忆化搜索+状态压缩)

题目链接:https://cn.vjudge.net/problem/UVA-10118

思路:设dp[pa][pb][pc][pd]四堆糖分别取到这四堆的第pa、pb、pc、pd颗时最多的pair数, 用一个二进制串记录篮中糖的状态(即哪些糖有那些没有)。状态转移一共四个,即分别从这四堆中拿出一颗糖放到篮子里,转移到放之后的状态。详见代码


#include<cstdio>
#include<vector>
#include<algorithm>
#include<map>
#include<cmath>
#include<cstring>
#include<sstream>
#include<iostream>
using namespace std;
const int maxn = 42;

int a[maxn], b[maxn], c[maxn], d[maxn]; //four piles
int DP[maxn][maxn][maxn][maxn];
int n;

inline bool Push(int pre, int m, int &st) // if she can take a pair of candies;
{
    bool ok = false;
    if(pre & (1<<m)) pre ^= (1<<m), ok = true;
    else pre |= (1<<m);
    st = pre;
    return ok;
}

int dp(int pa, int pb, int pc, int pd, int st, int num) // st : sugars that are in the basket
{
    int &ans = DP[pa][pb][pc][pd];
    if(ans >= 0) return ans;
    ans = 0;
    if(num < 5) {
       if(pa < n) {
          int st0;
          if(Push(st, a[pa], st0)) ans = max(ans, 1+dp(pa+1, pb, pc, pd, st0, num-1));
          else ans = max(ans, dp(pa+1, pb, pc, pd, st0, num+1));
       }
       if(pb < n) {
          int st0;
          if(Push(st, b[pb], st0)) ans = max(ans, 1+dp(pa, pb+1, pc, pd, st0, num-1));
          else ans = max(ans, dp(pa, pb+1, pc, pd, st0, num+1));
       }
       if(pc < n) {
          int st0;
          if(Push(st, c[pc], st0)) ans = max(ans, 1+dp(pa, pb, pc+1, pd, st0, num-1));
          else ans = max(ans, dp(pa, pb, pc+1, pd, st0, num+1));
       }
       if(pd < n) {
          int st0;
          if(Push(st, d[pd], st0)) ans = max(ans, 1+dp(pa, pb, pc, pd+1, st0, num-1));
          else ans = max(ans, dp(pa, pb, pc, pd+1, st0, num+1));
       }
    }
    return ans;
}

int main()
{
   while(scanf("%d", &n) && n) {
      memset(DP, -1, sizeof DP);
      for(int i = 0; i < n; i++)
         scanf("%d%d%d%d", &a[i], &b[i], &c[i], &d[i]);
      printf("%d\n", dp(0, 0, 0, 0, 0, 0));
   }
}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值