HDU 4272 LianLianKan (狀壓DP+DFS)題解

思路:

用狀壓DP+DFS遍歷查找是否可行。假設一個數爲x,那麼他最遠可以消去的點爲x+9,因爲x+1~x+4都能被他前面的點消去,所以我們將2進制的範圍設爲2^10,用0表示已經消去,1表示沒有消去。dp[i][j]表示棧頂是i當前狀態爲j時能不能消去棧頂,-1代表不知道,0不行,1行。所以我們只需DFS到i==n時j是否爲0,就可以知道能不能消除。更新狀態時,只有棧頂到棧底元素>10才更新新的元素進棧。

代碼:

#include<cstdio>
#include<map>
#include<set>
#include<queue>
#include<cstring>
#include<string>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define ll long long
const int maxn = 1 << 10;
const int MOD = 100000000;
const int INF = 0x3f3f3f3f;
using namespace std;
int n,num[maxn];
int dp[maxn][maxn]; //-1不知道,0不能除掉棧頂,1可以除掉棧頂
//0消去,1未消去
int nextsta(int pos,int sta){   //後面數字大於10纔有新數字加入
    if(n - pos <= 10) return sta >> 1;
    else return 1<<9 | sta>>1;
}
int dfs(int pos,int sta){
    if(pos == n) return sta == 0;
    if(dp[pos][sta] != -1) return dp[pos][sta];
    dp[pos][sta] = 0;
    if((sta&1) == 0)    //已經除掉棧頂了
        dp[pos][sta] = dfs(pos + 1,nextsta(pos,sta));
    else{
        int cnt = 0;
        for(int i = 1;i < 10 && cnt < 5;i++){
            if(sta&1<<i){
                cnt++;
                if(num[pos+i] != num[pos]) continue;
                int newsta = sta & ~1 & ~(1<<i);
                //sta & ~1 => 將棧頂歸零
                //& ~(1<<i) => 將某位歸零
                if(dfs(pos + 1,nextsta(pos,newsta))){
                    dp[pos][sta] = 1;
                    break;
                }
            }
        }
    }
    return dp[pos][sta];
}
int main(){
    while(~scanf("%d",&n)){
        for(int i = n-1;i >= 0;i--)
            scanf("%d",&num[i]);
        if(n % 2){
            printf("0\n");
            continue;
        }
        memset(dp,-1,sizeof(dp));
        int ans = dfs(0,(1<<min(10,n)) - 1);
        printf("%d\n",ans);
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章