Thought:D[a][b][c][d] said from the first basket took a sugar, the second took a B sugar, the third took a C sugar, the fourth to take a D sugar at most can also get how much candy. First of all understand a problem: if you can take a,b,c,d, regardless of how to take, the last basket of the remaining candy color and number are the same. So once you have searched for a state that has been searched, you can return directly and no further search is necessary.
AC Code:
#include <cstdio> #include <algorithm> #include <cstring> #include <utility> #include < string> #include <iostream> #include <map> #include <set> #include <vector> #include <
Queue> #include <stack> using namespace std;
#define EPS 1e-10 #define INF 0x3f3f3f3f #define PI pair<int, int> const int MAXN = 40 + 2;
int CAND[4][MAXN], n;
int D[MAXN][MAXN][MAXN][MAXN];
int top[4], bit[30];
void Init () {bit[0] = 1;
for (int i = 1; i <; ++i) bit[i] = bit[i-1] * 2;
} int dfs (int color, int cnt) {if (d[top[0]][top[1]][top[2]][top[3]]! = 1) return d[top[0]][top[1]][top[2]][top[3]];
if (cnt = = 5) return d[top[0]][top[1]][top[2]][top[3]] = 0;
int ans = 0;
for (int i = 0; i < 4; ++i) {if (Top[i] >= N) continue;
int col = ++top[i];
col = Bit[cand[i][col]];
if (col & color) {//basket already has the right color int a = 1 + DFS (Color-col, cnt-1);
ans = max (ans, a);
} else {int a = DFS (color + col, cnt + 1); Ans =Max (ans, a);
} top[i]--;
} return d[top[0]][top[1]][top[2]][top[3]] = ans;
} int main () {init ();
while (scanf ("%d", &n) = = 1 && N) {memset (d,-1, sizeof (d));
memset (top, 0, sizeof (top));
for (int i = 1; I <= n; ++i) for (int j = 0; j < 4; ++j) scanf ("%d", &cand[j][i]);
printf ("%d\n", DFS (0, 0));
} return 0; }
If there are any irregularities, please note.