题目大意:
有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;
}