SPOJ Problem Set (classical)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
Added by: | Bin Jin |
Date: | 2007-09-06 |
Time limit: | 5s |
Source limit: | 10000B |
Languages: | All except: C++ 4.0.0-8 |
Resource: | own problem |
题目:http://www.spoj.pl/problems/NQUEEN/
分析:这题也可以转化为DLX精确覆盖问题,将棋盘的 行 列 左斜线 右斜线 作为覆盖点,将每个格子作为操作,但是不同的是只需选折覆盖行,或者覆盖列,之前没有判断,直接扫描全部覆盖,一直无解,找了一个晚上加一个早上阿。。。速度还行,跑了0.5s
代码:
#include<cstdio> #define mm 777777 #define mn 3333 int U[mm],D[mm],L[mm],R[mm],C[mm],id[mm]; int H[mn],S[mn],Q[mn],P[mn],X[mn],Y[mn]; bool p[mn]; int n,size; void prepare(int r,int c) { for(int i=0;i<=c;++i) { S[i]=0; U[i]=D[i]=i; L[i+1]=i; R[i]=i+1; } R[size=c]=0; while(r)H[r--]=-1; } 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],--S[C[j]]; } void resume(int c) { L[R[c]]=R[L[c]]=c; for(int i=U[c];i!=c;i=U[i]) for(int j=L[i];j!=i;j=L[j]) ++S[C[U[D[j]]=D[U[j]]=j]]; } bool Dance(int k) { if(k>=n) { for(int i=0;i<k;++i)P[X[id[Q[i]]]]=Y[id[Q[i]]]; for(int i=1;i<n;++i)printf("%d ",P[i]); printf("%d\n",P[n]); return 1; } if(!R[0])return 0; int i,j,c,tmp=mm; for(i=R[0];i;i=R[i]) if(i<=n) { if(S[i]<tmp)tmp=S[c=i]; }else break; remove(c); for(i=D[c];i!=c;i=D[i]) { Q[k]=i; for(j=R[i];j!=i;j=R[j])remove(C[j]); if(Dance(k+1))return 1; for(j=L[i];j!=i;j=L[j])resume(C[j]); } resume(c); return 0; } void Link(int r,int c) { ++S[C[++size]=c]; id[size]=r; D[size]=D[c]; U[D[c]]=size; U[size]=c; D[c]=size; if(H[r]<0)H[r]=L[size]=R[size]=size; else { R[size]=R[H[r]]; L[R[H[r]]]=size; L[size]=H[r]; R[H[r]]=size; } } void place(int &p1,int &p2,int &p3,int &p4,int i,int j) { p1=j,p2=n+i,p3=n+n+i-j+n,p4=n+n+n+n-1+i+j-1; } int main() { int i,j,k,p1,p2,p3,p4; while(scanf("%d",&n)!=-1) { for(i=1;i<=n*6-2;++i)p[i]=0; prepare(n*n,n*6-2); for(k=i=1;i<=n;++i) { scanf("%d",&j); if(j) { place(p1,p2,p3,p4,i,j); p[p1]=p[p2]=p[p3]=p[p4]=1; Link(k,p1),Link(k,p2),Link(k,p3),Link(k,p4); X[k]=i,Y[k]=j; ++k; } } for(i=1;i<=n;++i) for(j=1;j<=n;++j) { place(p1,p2,p3,p4,i,j); if(p[p1]||p[p2]||p[p3]||p[p4])continue; Link(k,p1),Link(k,p2),Link(k,p3),Link(k,p4); X[k]=i,Y[k]=j; ++k; } Dance(0); } return 0; }