#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<algorithm> #include<cassert> #include<string> #include<sstream> #include<set> #include<vector> #include<stack> #include<map> #include<queue> #include<deque> #include<cstdlib> #include<cstdio> #include<cstring> #include<cmath> #include<ctime> #include<cctype> #include<functional> using namespace std; #define me(s) memset(s,0,sizeof(s)) #define pb push_back typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; typedef pair <int, int> P; const int maxr=5000; const int maxn=2000; const int maxnode=20000; struct DLX //DLX模板 { int n,sz; int S[maxn]; int row[maxnode],col[maxnode]; int L[maxnode],R[maxnode],U[maxnode],D[maxnode]; int ansd,ans[maxr]; void init(int n) { this->n=n; for(int i=0;i<=n;i++) { U[i]=i,D[i]=i,L[i]=i-1,R[i]=i+1; } R[n]=0,L[0]=n; sz=n+1; memset(S,0,sizeof(S)); } void addRow(int r,vector<int>columns) { int first=sz; for(int i=0;i<columns.size();i++) { int c=columns[i]; L[sz]=sz-1,R[sz]=sz+1,D[sz]=c,U[sz]=U[c]; D[U[c]]=sz,U[c]=sz; row[sz]=r;col[sz]=c; S[c]++,sz++; } R[sz-1]=first;L[first]=sz-1; } #define FOR(i,A,s) for(int i=A[s];i!=s;i=A[i]) void remove(int c) { L[R[c]]=L[c]; R[L[c]]=R[c]; FOR(i,D,c) FOR(j,R,i) { U[D[j]]=U[j],D[U[j]]=D[j],--S[col[j]]; } } void restore(int c) { FOR(i,U,c) FOR(j,L,i) { ++S[col[j]],U[D[j]]=j;D[U[j]]=j; } L[R[c]]=c;R[L[c]]=c; } bool dfs(int d) { if(R[0]==0) { ansd=d;return true; } int c=R[0]; FOR(i,R,0)if(S[i]<S[c])c=i; remove(c); FOR(i,D,c) { ans[d]=row[i]; FOR(j,R,i)remove(col[j]); if(dfs(d+1))return true; FOR(j,L,i)restore(col[j]); } restore(c); return false; } bool solve(vector<int>&v) { v.clear(); if(!dfs(0))return false; for(int i=0;i<ansd;i++) v.push_back(ans[i]); return true; } }; DLX solver; const int SLOT=0; const int ROW=1; const int COL=2; const int SUB=3; int encode(int a,int b,int c)//行,列的统一编码解码函数,从1开始编号,最大编号是1024 { return a*256+b*16+c+1; } void decode(int code,int&a,int&b,int&c) { code--; c=code%16;code/=16; b=code%16;code/=16; a=code; } char puzzle[16][20]; bool read() { for(int i=0;i<16;i++) if(scanf("%s",puzzle[i])!=1)return false; return true; } int main() { int rnd=0; while(read()) { if(rnd++)printf("\n"); solver.init(1024); //初始化1024列 for(int r=0;r<16;r++) for(int c=0;c<16;c++) for(int v=0;v<16;v++) if(puzzle[r][c]=='-'||puzzle[r][c]=='A'+v)//注意,已经填入字母v的格子也要算入 { vector<int>columns; //表示该行可以覆盖的列编号 columns.push_back(encode(SLOT,r,c)); columns.push_back(encode(ROW,r,v)); columns.push_back(encode(COL,c,v)); columns.push_back(encode(SUB,(r/4)*4+c/4,v));//(r,c)格子所在子方阵编号是(r/4)*4+c/4 solver.addRow(encode(r,c,v),columns); } vector<int>ans; assert(solver.solve(ans)); for(int i=0;i<ans.size();i++) { int r,c,v; decode(ans[i],r,c,v); puzzle[r][c]='A'+v; } for(int i=0;i<16;i++) printf("%s\n",puzzle[i]); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u014800748/article/details/47440795