刚做状态压缩DP。。思路和一般的DP一样,只是每次都对应一种状态。
目前只会最简单的。。用一个数的二进制表示一种状态。
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 5337 | Accepted: 2836 |
Description
Farmer John has purchased a lush new rectangular pasture composed of M byN (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
Output
Sample Input
2 3 1 1 1 0 1 0
Sample Output
9
Hint
1 2 3 4
这个就是最简单的一个题,首先初始化,把一行里满足的情况用st数组记下(先假设图中的每个地方都可以种植物,st里的情况只保证没有相邻的植物),判断有没有相邻的是i&(i<<1)。接着再用数组a[i]记下来第i行不满足题意的情况,比如第2行010,a[2]=101,到时再把情况和a进行&运算,答案必须是0才成立。接下来就是DP,dp[i][j]代表第i行状态是j(st[j])的情况有多少种满足的,先初始化,如果第j个状态满足,那么dp[1][j]=1,假设第i-1行l状态和i行j状态不矛盾,那么dp[i][j]=dp[i][j]+dp[i-1][l],判断第i行和第i-1行是否矛盾也要用&运算(不能对应的位置都是1)。
#include
#include
#include
#include
#include
#include
#include
#include
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 15946 | Accepted: 6056 |
Description
Input
Output
Sample Input
5 4 PHPP PPHH PPPP PHPP PHHP
Sample Output
6
这个比上一个难一些,因为附近两格之内都不能再有,因此dp数组变成了三维的,dp[i][j][k]代表第i-1行状态是j,第i行状态是k,这样循环也要多一层,判断是否矛盾的时候要把两行都判断,先判断这两行满不满足,如果满足,再枚举这两行上一行的情况。题目问的是最多能放多少个炮,那么用cnt[i]数组记录状态i时的一行有多少个炮(多少个1),在所有都不矛盾的情况下,dp[i][j][k]=max(dp[i][j][k],dp[i-1][l][j]+cnt[k])。在初始化函数里算cnt,如果想知道状态i有多少个1,就让i=i&(i-1),直到i=0,能进行多少次就有多少个1(每进行一次最后那个1就变成0)。
#include
#include
#include
#include
#include
#include
#include
#include