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;
}

 

转载于:https://www.cnblogs.com/KirinSB/p/9408766.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值