Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 7546 | Accepted: 4025 |
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
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
Sample Input
2 3 1 1 1 0 1 0
Sample Output
9
从上往下,从左往右遍历,会发现,当前点只跟上一行和左边这个点有关系,所以我们记录的状态就是dp[i][j][sta]当前点i,j以及上一行和左边点的状态sta < (1<<13)。
#include <iostream> #include <cstdio> using namespace std; const int maxn = 1<<13 + 1; const int mod = 100000000; int dp[13][13][maxn] , N , M , mp[13][13]; void initial(){ for(int i = 0; i < 13; i++){ for(int j = 0; j < 13; j++){ mp[i][j] = 0; for(int k = 0; k < maxn; k++) dp[i][j][k] = -1; } } } int DP(int i , int j , int k){ if(i >= N) return 1; if(dp[i][j][k] != -1) return dp[i][j][k]; int ans = 0; if(mp[i][j]==0 || (k&(1<<j)) > 0 || (k&(1<<M)) > 0){ int sta = (k&((1<<M)-1)); if((sta&(1<<j)) > 0) sta = (sta-(1<<j)); if(j+1>=M) return dp[i][j][k] = DP(i+1 , 0 , sta)%mod; return dp[i][j][k] = DP(i , j+1 , sta)%mod; }else{ int sta = (k|(1<<j)); if(j+1 >= M){ sta = (sta&((1<<M)-1)); ans = (ans+DP(i+1 , 0 , sta))%mod; }else{ sta = (sta|(1<<M)); ans = (ans+DP(i , j+1 , sta))%mod; } sta = (sta&((1<<M)-1)); if((sta&(1<<j)) > 0) sta = sta-(1<<j); if(j+1>=M) ans = (ans+DP(i+1 , 0 , sta))%mod; else ans = (ans+DP(i , j+1 , sta))%mod; return dp[i][j][k] = ans%mod; } } void readcase(){ for(int i = 0; i < N; i++){ for(int j = 0; j < M; j++) scanf("%d" , &mp[i][j]); } } void computing(){ printf("%d\n" , DP(0 , 0 , 0)); } int main(){ while(~scanf("%d%d" , &N , &M)){ initial(); readcase(); computing(); } return 0; }