1771. Yet Another N-Queen ProblemProblem code: NQUEEN |
After solving Solution to the n Queens Puzzle by constructing, LoadingTime wants to solve a harder version of the N-Queen Problem. Some queens have been set on particular locations on the board in this problem. Can you help him??
The input contains multiple test cases. Every line begins with an integer N (N<=50), then N integers followed, representing the column number of the queen in each rows. If the number is 0, it means no queen has been set on this row. You can assume there is at least one solution.
For each test case, print a line consists of N numbers separated by spaces, representing the column number of the queen in each row. If there are more than one answer, print any one of them.
Input: 4 0 0 0 0 8 2 0 0 0 4 0 0 0 Output: 2 4 1 3 2 6 1 7 4 8 3 5
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N=100000; const int M=N*5; int l[M], r[M], d[M], u[M], col[M], row[M]; int control[2000]; int h[N], res[N]; int dcnt = 0; int n; inline void addnode(int &x) { ++x; r[x]=l[x]=u[x]=d[x]=x; } inline void insert_row(int rowx, int x) { r[l[rowx]]=x; l[x]=l[rowx]; r[x]=rowx; l[rowx]=x; } inline void insert_col(int colx, int x) { d[u[colx]]=x; u[x]=u[colx]; d[x]=colx; u[colx]=x; } void dlx_init(int cols) { memset(h, -1, sizeof(h)); memset(control, 0, sizeof(control)); dcnt=-1; addnode(dcnt); for(int i=1;i<=cols;++i) { addnode(dcnt); insert_row(0, dcnt); } } void remove(int c) { l[r[c]]=l[c]; r[l[c]]=r[c]; for(int i=d[c];i!=c;i=d[i]) for(int j=r[i];j!=i;j=r[j]) { u[d[j]]=u[j]; d[u[j]]=d[j]; control[col[j]]--; } } void resume(int c) { for(int i=u[c];i!=c;i=u[i]) for(int j=l[i];j!=i;j=l[j]) { u[d[j]]=j; d[u[j]]=j; control[col[j]]++; } l[r[c]]=c; r[l[c]]=c; } bool DLX(int deep) { if(deep==n || r[0]==0) { sort(res, res+deep); for(int i=0;i<deep;i++) printf("%d ", res[i]%300); puts(""); return true; } int min=M, tempc; for(int i=r[0];i!=0;i=r[i]) if(control[i]<min && i<=n+n) { min=control[i]; tempc=i; } remove(tempc); for(int i=d[tempc];i!=tempc;i=d[i]) { res[deep]=row[i]; for(int j=r[i];j!=i;j=r[j]) remove(col[j]); if(DLX(deep+1)) return true; for(int j=l[i];j!=i;j=l[j]) resume(col[j]); } resume(tempc); return false; } inline void insert_node(int x, int y) { control[y]++; addnode(dcnt); row[dcnt]=x; col[dcnt]=y; insert_col(y, dcnt); if(h[x]==-1) h[x]=dcnt; else insert_row(h[x], dcnt); } int num[333]; int main() { #ifdef ACM freopen("in.txt", "r", stdin); #endif while(~scanf("%d", &n)) { dlx_init(n+n+(2*n-1)*2); for(int i=0;i<n;i++) scanf("%d", num+i+1); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(num[i]==0 || num[i]==j) { insert_node((i-1)*300+j, i); insert_node((i-1)*300+j, n+j); insert_node((i-1)*300+j, n+n+(i+j-1)); insert_node((i-1)*300+j, n+n+(2*n-1)+(n+i-j)); } DLX(0); } }