zoukankan      html  css  js  c++  java
  • 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
    ");
                continue;
            }
            memset(dp,-1,sizeof(dp));
            int ans = dfs(0,(1<<min(10,n)) - 1);
            printf("%d
    ",ans);
        }
        return 0;
    }
    
    
  • 相关阅读:
    Python入门篇-解析式、生成器
    使用Kerberos进行Hadoop认证
    Python标准库-datatime和time
    使用Cloudera Manager部署HUE
    使用Cloudera Manager部署oozie
    使用Cloudera Manager部署Spark服务
    HDFS重启集群导致数据损坏,使用fsck命令修复过程
    关系型数据的收集
    使用Cloudera Manager搭建Kudu环境
    分布式结构化存储系统-Kudu简介
  • 原文地址:https://www.cnblogs.com/KirinSB/p/9408766.html
Copyright © 2011-2022 走看看