POJ-1321 board Problem n queen problem (Binary Version)

Source: Internet
Author: User

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;}
  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.