1. 程式人生 > >Free Candies(記憶化搜尋)

Free Candies(記憶化搜尋)

給出4堆糖,往容量為5籃子裡裝任意一個在堆頂的糖,籃子裡有相同顏色的就拿走,問最多能拿走幾次。

定義四維陣列記憶搜尋。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=45;
bool bas[25];
int n,piles[4][maxn],k[maxn][maxn][maxn][maxn];
int dp(int a,int b,int c,int d){
    int& best=k[a][b][c][d];
    if(best!=-1) return best;
    if(count(bas,bas+25,true)==5) return best=0;
    if(a==n&&b==n&&c==n&&d==n) return best=0;
    if(a!=n){
        bool& p=bas[piles[0][a]];
        p=!p;
        best=max(best,dp(a+1,b,c,d)+(p?0:1));
        p=!p;
    }
    if(b!=n){
        bool& p=bas[piles[1][b]];
        p=!p;
        best=max(best,dp(a,b+1,c,d)+(p?0:1));
        p=!p;
    }
    if(c!=n){
        bool& p=bas[piles[2][c]];
        p=!p;
        best=max(best,dp(a,b,c+1,d)+(p?0:1));
        p=!p;
    }
    if(d!=n){
        bool& p=bas[piles[3][d]];
        p=!p;
        best=max(best,dp(a,b,c,d+1)+(p?0:1));
        p=!p;
    }
    return best;
}
int main(){
    while(scanf("%d",&n),n){
        memset(k,-1,sizeof(k));
        memset(bas,0,sizeof(bas));
        memset(piles,0,sizeof(piles));
        for(int i=0;i<n;++i)
            for(int j=0;j<4;++j)
                scanf("%d",&piles[j][i]);
        printf("%d\n",dp(0,0,0,0));
    }
    return 0;
}