题目链接: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));
}
}