POJ-1321 board Problem n queen problem (Binary Version)
Give an n * n board, which cannot contain pawns in some places.
Now you are asked to place k pieces on the board so that any two of these pieces are not in the same column. How many methods are there?
Solution: similar to the problem of Queen n, it can be processed in one row. The value 1 in binary indicates that the location is retainable, and the value 0 indicates that the location is not retainable, all indicates the status where each row can be put (1 <n)-1)
If the column state is s, s & (restriction of the row) & All is the final state of the row.
Now we only need to find all the 1 in this final state, so how can we quickly find this 1
If the final state is ss, then ss & (-ss) & All is the first 1 position (which can be verified by yourself ), set a while loop to find All 1. Remember & All
#include
#includeusing namespace std;const int N = 20;char str[N];int n, k, ans, All, statu[N];void init() { All = (1 << n) - 1; for(int i = 0; i < n; i++) { gets(str); statu[i] = All; for(int j = 0; j < n; j++) if(str[j] == '.') statu[i] ^= (1 << j); } ans = 0;}void solve(int cur, int num, int s) { if(num == k) { ans++; return ; } if(cur == n || n - cur + num < k) return ; int ss = (s & statu[cur]) & All; while(ss) { int t = ss & (-ss) & All; solve(cur + 1, num + 1, s ^ t); ss = (ss ^ t )& All; } solve(cur + 1, num, s);}int main() { while(gets(str)) { sscanf(str,"%d%d", &n, &k); if(n == -1 && k == -1) break; init(); solve(0,0,All); printf("%d\n", ans); } return 0;}