[DLX 精确覆盖 模板题] HUST 1017 Exact cover

题目链接

关于DancingLinks可以戳这里 超详细 走心!

#include
#include
#include
using namespace std;

inline char nc(){
  static char buf[100000],*p1=buf,*p2=buf;
  return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline bool read(int &x){
  char c=nc(),b=1;
  for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1; else if (c==EOF) return 0;
  for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b; return 1;
}

const int N=1005;
const int M=2000005;

int ncnt;
int L[M],R[M],U[M],D[M],row[M],col[M];
int size[N];
int ans[N],pnt;

inline void del(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],size[col[j]]--;
}
inline void rec(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])
      U[D[j]]=D[U[j]]=j,size[col[j]]++;
}

inline bool dance(){
  if (R[0]==0){
    printf("%d ",pnt); sort(ans+1,ans+pnt+1);
    for (int i=1;i<=pnt;i++) printf("%d ",ans[i]); printf("\n");
    return 1;
  }
  int minv=1<<30,c=0;
  for (int i=R[0];i;i=R[i]) if (size[i]for (int i=D[c];i!=c;i=D[i]){
    ans[++pnt]=row[i];
    for (int j=R[i];j!=i;j=R[j]) del(col[j]);
    if (dance()) return 1;
    for (int j=L[i];j!=i;j=L[j]) rec(col[j]);
    ans[pnt--]=0;
  }
  rec(c);
  return 0;
}

int n,m;

int main(){
  int k,x;
  freopen("t.in","r",stdin);
  freopen("t.out","w",stdout);
  while (read(n) && read(m)){
    for (int i=1;i<=m;i++)
      L[i]=i-1,R[i]=i+1,U[i]=D[i]=i,size[i]=0;
    L[0]=m,R[0]=1; R[m]=0; ncnt=m;
    for (int i=1;i<=n;i++){
      read(k);
      for (int j=ncnt+1;j<=ncnt+k;j++){
    read(x); size[x]++;
    row[j]=i,col[j]=x;
    L[j]=j-1,R[j]=j+1;
    D[j]=x,U[j]=U[x];
    D[U[j]]=j,U[D[j]]=j;
      }
      R[ncnt+k]=ncnt+1; L[ncnt+1]=ncnt+k;
      ncnt+=k;
    }
    pnt=0;
    if (!dance()) printf("NO\n");
  }
  return 0;
}

你可能感兴趣的:(搜索剪枝,Dancing,Links)