题目大意是给了4堆糖果,每一堆糖果里面都有各种各样的糖果,我们每次可以取每一堆糖果顶端的糖果放在篮子里,篮子里最多放
不超过5种糖果,如果篮子里有一对一样的糖果,就把那一对糖果放在口袋里,问口袋最多能放几个糖果
思路
记忆化搜索
既然只有4堆糖果,我们每次取法总会重复计算一些状态,将状态记忆化, d(a, b, c, d){1 <= a, b, c, d <= n} 表示当前第一堆糖果已经
到了第a个,第二堆糖果到了第b个,以此类推,用递归记忆化搜索即可。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 40 + 3;
int n;
int p[5][maxn];
int dp[maxn][maxn][maxn][maxn];
int getMax(int a, int b, int c, int d){
int & res = dp[a][b][c][d];
if(res != -1) return res;
int pack[21], o[4]; o[0] = a; o[1] = b; o[2] = c; o[3] = d;
memset(pack, 0, sizeof(pack));
int cnt = 0, tot = 0;
for(int j = 0; j < 4; ++j)
for(int i = 1; i <= o[j]; ++i){
int v = p[j + 1][i];
pack[v]++;
}
for(int i = 1; i <= 20; ++i) {
tot += pack[i] / 2;
if(pack[i] % 2 == 1) cnt++;
}
res = tot;
if(cnt >= 5) return res;
if(a + 1 <= n) res = max(res, getMax(a + 1, b, c, d));
if(b + 1 <= n) res = max(res, getMax(a, b + 1, c, d));
if(c + 1 <= n) res = max(res, getMax(a, b, c + 1, d));
if(d + 1 <= n) res = max(res, getMax(a, b, c, d + 1));
return res;
}
int main()
{
while(scanf("%d", &n) && n){
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= 4; ++j)
scanf("%d", &p[j][i]);
memset(dp, -1, sizeof(dp));
printf("%d\n", getMax(0, 0, 0, 0));
}
return 0;
}