思路:d[a][b][c][d]表示從已經第一個籃子取了a顆糖,第二個取了b顆糖,第三個取了c顆糖,第四個取了d顆糖最多還能夠獲得多少糖果。首先明白一個問題:如果能分別取a,b,c,d個,不論如何取,最后籃子中剩余的糖果顏色和個數都是一樣的。那么一旦搜索到一個已經被搜索過得狀態,直接返回即可,沒必要繼續搜索。
AC代碼:
#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 < 22; ++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) { //籃子中已經右該顏色 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;}如有不當之處歡迎指出!
新聞熱點
疑難解答