POJ3254(状压dp)

本文介绍了一种利用状态压缩动态规划(状压DP)的经典算法来解决牧場种植玉米的问题,确保种植区域不相邻且避开不肥沃的土地。通过详细解析代码和算法流程,展示了如何计算所有可能的种植方案。
Corn Fields
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 16310 Accepted: 8613

Description

Farmer John has purchased a lush new rectangular pasture composed of M by N (1 ≤ M ≤ 12; 1 ≤ N ≤ 12) square parcels. He wants to grow some yummy corn for the cows on a number of squares. Regrettably, some of the squares are infertile and can't be planted. Canny FJ knows that the cows dislike eating close to each other, so when choosing which squares to plant, he avoids choosing squares that are adjacent; no two chosen squares share an edge. He has not yet made the final choice as to which squares to plant.

Being a very open-minded man, Farmer John wants to consider all possible options for how to choose the squares for planting. He is so open-minded that he considers choosing no squares as a valid option! Please help Farmer John determine the number of ways he can choose the squares to plant.

Input

Line 1: Two space-separated integers:  M and  N 
Lines 2.. M+1: Line  i+1 describes row  i of the pasture with  N space-separated integers indicating whether a square is fertile (1 for fertile, 0 for infertile)

Output

Line 1: One integer: the number of ways that FJ can choose the squares modulo 100,000,000.

Sample Input

2 3
1 1 1
0 1 0

Sample Output

9

Hint

Number the squares as follows:
1 2 3
  4  

There are four ways to plant only on one squares (1, 2, 3, or 4), three ways to plant on two squares (13, 14, or 34), 1 way to plant on three squares (134), and one way to plant on no squares. 4+3+1+1=9.

Source

USACO 2006 November Gold


解题思路:状压dp经典题,dp[i][j]表示前i行状态为j的合法方案数,把j想象成一个M位的二进制数,每一位的0表示不放牧,1表示放牧,那么我们首先判断j这个状态本身是否合法(存在两个相连点的放牧或者有一个点本身不能放牧但是这个状态表示这里放牧),如果不合法则dp[i][j] = 0,如果合法,我们从i的前一行的所有合法状态进行转移,但是并不是所有的状态多可以转移过来,只有与当前行的状态j相容才能转移过来,也就是不会出现对于某一位在一列的出现都放牧的情况(不满足不能相连放牧的要求)。

#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long LL;
const LL mod = 1e9;
int N, M;
LL dp[20][5000];
int s[20][20];
int term[20];
int temp[20];
void init()
{
    memset(dp, 0, sizeof(dp));
}
bool judge(int row, int x1, int x2)
{
    //先判断x1状态是否合法
    int cnt1 = M;
    for(int j = 0; j < M; j++)
    {
        int num = (x1>>j)&1;
        term[cnt1--] = num;
    }
    for(int j = 1; j <= M; j++)
    {
        if(s[row][j] == 1 && term[j] == 0)
        {
            return false;
        }
    }
    for(int j = 1; j < M; j++)
    {
        if(term[j] == 0) continue;
        else
        {
            if(s[row][j] == 1) continue;
            else
            {
                if(s[row][j + 1] == 1) continue;
                else if(term[j + 1] == 1)
                {
                    return false;
                }
            }
        }
    }
    int cnt2 = M;
    for(int j = 0; j < M; j++)
    {
        int num = (x2>>j)&1;
        temp[cnt2--] = num;
    }
    for(int j = 1; j <= M; j++)
    {
       if(term[j] == 1 && temp[j] == 1)
       {
           if(s[row][j] == 1 || s[row - 1][j] == 1) continue;
           else return false;
       }
    }
    return true;
}
int main()
{
    while(~scanf("%d%d", &N, &M))
    {
        for(int i = 1; i <= N; i++)
        {
            for(int j = 1; j <= M; j++)
            {
                scanf("%d", &s[i][j]);
                if(s[i][j]) s[i][j] = 0;
                else s[i][j] = 1;
            }
        }
        init();
        int cnt;
        for(int i = 0; i < (1<<M); i++)
        {
            dp[1][i] = 1;
            cnt = M;
            for(int j = 0; j < M; j++)
            {
                int num = (i>>j)&1;
                term[cnt--] = num;
            }
            for(int j = 1; j <= M; j++)
            {
                if(s[1][j] == 1 && term[j] == 0)
                {
                    dp[1][i] = 0;
                    break;
                }
            }
            for(int j = 1; j < M; j++)
            {
                if(term[j] == 0) continue;
                else
                {
                    if(s[1][j] == 1) continue;
                    else
                    {
                        if(s[1][j + 1] == 1) continue;
                        else if(term[j + 1] == 1)
                        {
                            dp[1][i] = 0;
                            break;
                        }
                    }
                }
            }
        }
        for(int i = 2; i <= N; i++)
        {
            for(int j = 0; j < (1<<M); j++)
            {
                for(int k = 0; k < (1<<M); k++)
                {
                    if(judge(i, j, k)) dp[i][j] = (dp[i][j] + dp[i - 1][k]) % mod;
                }
            }
        }
        LL sum = 0;
        for(int i = 0; i < (1<<M); i++)
        {
            sum = (sum + dp[N][i]) % mod;
        }
        printf("%I64d\n", sum);
    }
    return 0;
}



DP超详细教程:从入门到精通 DP缩动态规划)是一种非常实用的算法技巧,特别适合处理态可以用二进制表示的问题。下面我将用最详细、最系统的方式讲解这个技术,保证你能彻底理解。 一、DP的本质 1.1 什么是缩? 缩的核心思想是:用二进制位来表示某种态。比如: 有5个灯泡:可以用5位二进制数表示它们的开关态 10101表示第1、3、5个灯亮,2、4灭 有8个任务是否完成:可以用8位二进制数表示 11001001表示第1、2、5、8个任务已完成 1.2 为什么需要态? 传统DP在表示某些态时会遇到困难。例如: 棋盘放置问题:要记录哪些格子被占用 任务分配问题:要记录哪些任务已被分配 路径问题:要记录哪些点已经访问过 如果用传统数组表示,可能需要多维数组,空间复杂度爆炸。而用二进制缩,一个整数就能表示复杂的态。 二、DP的三大组成部分 2.1 态表示 用一个整数的二进制形式表示态: 每一位代表一个元素的态(选中/未选中,存在/不存在等) 整数范围:0到2ⁿ-1(n是元素个数) 示例:3个物品的选择态 000(0):都没选 001(1):选第1个 010(2):选第2个 011(3):选第1、2个 ... 111(7):全选 2.2 态转移 定义如何从一个态转移到另一个态,通常包括: 检查当前态的某些位 根据条件修改某些位 生成新态 2.3 DP数组设计 dp[state]或dp[state][i],其中: state是缩后的态 i可能是附加信息(如当前位置、已选数量等) 三、必须精通的位运算技巧 3.1 基本操作 操作 代码表示 示例(假设8位二进制) 设置第i位为1 `state (1 << i)` `0010 (1<<2) → 0110` 设置第i位为0 state & ~(1 << i) 0110 & ~(1<<2) → 0010 切换第i位 state ^ (1 << i) 0110 ^ (1<<2) → 0010 检查第i位是否为1 (state >> i) & 1 (0110 >> 2) & 1 → 1 3.2 高级技巧 枚举所有子集: cpp for(int subset = state; subset; subset = (subset-1)&state){ // 处理subset } 最低位的1: cpp int lowbit = x & -x; 统计1的个数: cpp int count = __builtin_popcount(state); // GCC内置函数 六、DP的优化技巧 6.1 预处理合法态 很多问题中,大部分态是不合法的,可以预先筛选: cpp vector<int> valid_states; for (int state = 0; state < (1 << n); ++state) { if (check(state)) { // 检查state是否合法 valid_states.push_back(state); } } 6.2 滚动数组优化 当态只依赖前一个阶段时,可以节省空间: cpp vector<vector<int>> dp(2, vector<int>(size)); // 只保留当前和上一个态 int now = 0, prev = 1; for (int i = 1; i <= n; ++i) { swap(now, prev); for (auto& state : valid_states) { dp[now][state] = 0; // 清空当前态 // 态转移... } } 6.3 记忆化搜索实现 有时递归形式更直观: cpp int memo[1<<20][20]; // 记忆化数组 int dfs(int state, int u) { if (memo[state][u] != -1) return memo[state][u]; // 递归处理... return memo[state][u] = res; } 七、常见问题与调试技巧 7.1 常见错误 位运算优先级:总是加括号,如(state & (1 << i)) 数组越界:态数是2ⁿ,不是n 初始态设置错误:比如TSP中dp[1][0] = 0 边界条件处理不当:如全选态是(1<<n)-1,不是1<<n 7.2 调试建议 打印中间态:将二进制态转换为可视化的形式 cpp void printState(int state, int n) { for (int i = n-1; i >= 0; --i) cout << ((state >> i) & 1); cout << endl; } 从小规模测试用例开始(如n=3,4) 使用assert检查关键假设 八、学习路线建议 初级阶段: 练习基本位操作 解决简单问题(如LeetCode 464、526题) 中级阶段: 掌握经典模型(TSP、棋盘覆盖) 学习优化技巧(预处理、滚动数组) 高级阶段: 处理高维(如需要同时缩多个态) 结合其他算法(如BFS、双指针) 九、实战练习题目推荐 入门题: LeetCode 78. Subsets(理解态表示) LeetCode 464. Can I Win(简单DP) 中等题: LeetCode 526. Beautiful Arrangement LeetCode 691. Stickers to Spell Word 经典题: POJ 2411. Mondriaan's Dream(棋盘覆盖) HDU 3001. Travelling(三进制) 挑战题: Codeforces 8C. Looking for Order Topcoder SRM 556 Div1 1000. LeftRightDigitsGame2 记住,掌握DP的关键在于: 彻底理解二进制态表示 熟练运用位运算 通过大量练习培养直觉 希望这份超详细的教程能帮助你彻底掌握DP!如果还有任何不明白的地方,可以针对具体问题继续深入探讨。 请帮我转成markdown语法输出,谢谢
最新发布
08-13
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值