题干
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
题解
#include<cstdio>
#include<iostream>
#include<bitset>
#include<cstring>
#include<vector>
using namespace std;
typedef long long ll;
int const MOD = 1e8;
bitset<15>bit[15];//用bitset进行保存
ll dp[15][1<<13];//状态压缩只能压缩m位,其中(1<<m) < 1e8 ,因为如果再大
//就开不了这样的数组了
vector<int> valid;
//找出符合条件的数,比如0,1,2,4,5可以,3,6,7不可以
void init_valid(){
valid.clear();
for(int i=0;i<(1<<13);i++){
if(i&(i<<1))continue;
valid.push_back(i);
}
}
//检查当前status是否满足r行的条件
bool check(int status,int r){
int rstatus = bit[r].to_ulong();
//合理应用位运算
if(!(status&(~rstatus)))return true;
return false;
}
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int N,M,in;
cin>>M>>N;
for(int i=1;i<=M;i++){
bit[i].reset();
for(int j=0;j<N;j++){
cin>>in;
if(in)bit[i].set(j);
}
}
memset(dp,0,sizeof(dp));
dp[0][0] = 1;
init_valid();
for(int i=1;i<=M;i++){
int tmp1 = bit[i].to_ulong();
int tmp2 = bit[i-1].to_ulong();
for(int j=0;j<valid.size()&&valid[j]<=tmp1;j++){
if(check(valid[j],i)){
for(int k=0;k<valid.size()&&valid[k]<=tmp2;k++){
//因为用到了状态压缩,所以,判断是否满足条件的时候
//复杂度降到了O(1),如果不用状态压缩,那么,就要
//每位每位的比较判断,所以之所以状态压缩比较好,
//有一个原因是计算机进行位运算的时候速度超快
if(check(valid[k],i-1)&&!(valid[k]&valid[j])){
dp[i][valid[j]] += dp[i-1][valid[k]];
}
}
}
}
}
int tmp = bit[M].to_ulong();
ll ans = 0;
for(int i=0;i<valid.size()&&valid[i]<=tmp;i++){
ans = (ans + dp[M][valid[i]])%MOD;
}
printf("%I64d\n",ans);
return 0;
}