1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
#include<bits/stdc++.h> using namespace std; inline int rd(){ int x=0,y=1;char c=getchar(); while(!isdigit(c)){if(c=='-')y=-y;c=getchar();} while(isdigit(c))x=x*10+c-'0',c=getchar(); return x*y; } struct DLX{ #define maxnode 1000010 #define maxn 1010 int n,m,tot; //n行 m列 现在一共有tot个元素 int U[maxnode],D[maxnode],L[maxnode],R[maxnode]; //U D L R 表示每个点四个方向所指向的节点编号 int Row[maxnode],Col[maxnode]; //Row Col 表示每个点所在的行号和列号 int H[maxn],num[maxn]; //H 是每行的开始位置 num 是每一列有多少个元素 int ansnum,ans[maxn]; //记录答案,表示我们选择了哪些行 inline void init(int N,int M){ n=N,m=M; for(int i=0; i<=m; i++){ num[i]=0; U[i]=D[i]=i; L[i]=i-1; R[i]=i+1; } L[0]=m; R[m]=0; tot=m; for(int i=1; i<=n; i++)H[i]=-1; } inline void add(int x,int y){//在x行y列插入一个元素 tot++; Col[tot]=y; Row[tot]=x; num[y]++; D[tot]=D[y]; U[D[y]]=tot; U[tot]=y; D[y]=tot; //在第y列的列首元素下面插入当前元素 if(H[x]<0){//如果第x行为空,那么将当前元素设为行首元素 H[x]=L[tot]=R[tot]=tot; } else{//否则在第x行的第一个元素后插入当前元素 R[tot]=R[H[x]]; L[R[H[x]]]=tot; L[tot]=H[x]; R[H[x]]=tot; } } inline void remove(int y){//将第y列删除,并删除第y列中所有元素所在的行 L[R[y]]=L[y]; R[L[y]]=R[y]; for(int i=D[y]; i!=y; i=D[i]){ for(int j=R[i]; j!=i; j=R[j]){ U[D[j]]=U[j]; D[U[j]]=D[j]; num[Col[j]]--; } } } inline void restore(int y){//反过来,进行恢复 L[R[y]]=y; R[L[y]]=y; for(int i=U[y]; i!=y; i=U[i]){ for(int j=L[i]; j!=i; j=L[j]){ U[D[j]]=j; D[U[j]]=j; num[Col[j]]++; } } } bool dance(int deep){ if(R[0]==0){ ansnum=deep; return true; } int now=R[0]; for(int i=R[0]; i!=0; i=R[i]){ if(num[i]<num[now])now=i; } //找到列中包含1最少的列,因为这样可以减少dfs的分支 remove(now); for(int i=D[now]; i!=now; i=D[i]){ ans[deep]=Row[i]; for(int j=R[i]; j!=i; j=R[j])remove(Col[j]); if(dance(deep+1))return true; for(int j=L[i]; j!=i; j=L[j])restore(Col[j]); } restore(now); return false; } #undef maxnode #undef maxn }dlx; inline void init(){ int n=rd(),m=rd(); dlx.init(n,m); for(int i=1; i<=n; i++){ for(int j=1; j<=m; j++){ int x=rd(); if(x)dlx.add(i,j); } } } inline void work(){ if(dlx.dance(0)){ for(int i=0; i<dlx.ansnum; i++){ printf("%d ",dlx.ans[i]); } puts(""); } else puts("No Solution!"); } int main(){ init(); work(); return 0; } |