利用移位操作来表示集合,同时要记录每一个堆的当前的堆顶的位置(利用代码中的top数组),还要记录当前的篮子中已经放置的糖果的数量,每次取出一个糖果的时候,按照与操作判断该种颜色的糖果是否已经已经放在篮子里面了,如果放在篮子里面则执行取出操作,注意需要同时从集合中以及篮子中取出该糖果,集合中去除的是颜色,篮子中去除的是数量,如果集合中没有该颜色的糖果,则将相应的颜色加入到集合中,同时将篮子中糖果的数量加1,再进行下一轮的递归操作,直到最终结果,具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
using namespace std;
int N;
int res[45][45][45][45];
int heap[45][4];
int dp(int* top,int s,int container){
int& ans = res[top[0]][top[1]][top[2]][top[3]];
if (ans >= 0) return ans;
if (top[0] == N&&top[1] == N&&top[2] == N&&top[3] == N || container == 5){
ans = 0;
return ans;
}
for (int i = 0; i < 4; i++){
if (top[i] < N){
int s1 = 1 << heap[top[i]][i];
top[i]++;
if (s1&s){
ans = max(ans, dp(top, s - s1, container - 1) + 1);
}
else if (container<5){
ans = max(ans, dp(top, s + s1, container + 1));
}
top[i]--;
}
}
return ans;
}
int main(){
while (cin >> N&&N){
for (int i = 0; i < N; i++){
for (int j = 0; j < 4; j++){
cin >> heap[i][j];
}
}
memset(res, -1, sizeof(res));
int top[] = { 0, 0, 0, 0};
cout << dp(top, 0, 0) << endl;
}
return 0;
}