搜索(DLX):HOJ 1017 - Exact cover

时间:2022-08-21 13:49:16

1017 - Exact cover

Time Limit: 15s Memory Limit: 128MB

Special Judge Submissions: 6751 Solved: 3519
Description
There is an N*M matrix with only 0s and 1s, (1 <= N,M <= 1000). An exact cover is a selection of rows such that every column has a 1 in exactly one of the selected rows. Try to find out the selected rows.
Input
There are multiply test cases. First line: two integers N, M; The following N lines: Every line first comes an integer C(1 <= C <= 100), represents the number of 1s in this row, then comes C integers: the index of the columns whose value is 1 in this row.
Output
First output the number of rows in the selection, then output the index of the selected rows. If there are multiply selections, you should just output any of them. If there are no selection, just output "NO".
Sample Input
6 7
3 1 4 7
2 1 4
3 4 5 7
3 3 5 6
4 2 3 6 7
2 2 7
Sample Output
3 2 4 6

这大概就是DLX的模板题了。
 #include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int N=,M=N*N;
int L[M],R[M],U[M],D[M];
int H[N],C[N],row[M],col[M];
int cnt,n,m,ans[N];
struct DLX{
void Init(int n,int m){
for(int i=;i<=m;i++){
L[i]=i-;R[i]=i+;
C[i]=;U[i]=D[i]=i;
}cnt=L[]=m;R[m]=;
for(int i=;i<=n;i++)H[i]=;
}
void Link(int r,int c){
++cnt;C[c]++;
col[cnt]=c;row[cnt]=r;
U[D[c]]=cnt;U[cnt]=c;
D[cnt]=D[c];D[c]=cnt;
if(H[r]){
R[cnt]=R[H[r]];L[cnt]=H[r];
L[R[H[r]]]=cnt;R[H[r]]=cnt;
}
else H[r]=L[cnt]=R[cnt]=cnt;
}
void Delete(int c){
R[L[c]]=R[c];L[R[c]]=L[c];
for(int i=D[c];i!=c;i=D[i])
for(int j=R[i];j!=i;j=R[j])
--C[col[j]],U[D[j]]=U[j],D[U[j]]=D[j];
}
void Resume(int c){
R[L[c]]=c;L[R[c]]=c;
for(int i=U[c];i!=c;i=U[i])
for(int j=L[i];j!=i;j=L[j])
++C[col[j]],U[D[j]]=j,D[U[j]]=j;
}
bool Dance(int dep){
if(!R[]){
printf("%d",dep);
for(int i=;i<=dep;i++)
printf(" %d",ans[i]);
puts("");return true;
}int p=;
for(int i=R[];i;i=R[i])
if(!p||C[p]>C[i])p=i;
Delete(p);
for(int i=D[p];i!=p;i=D[i]){
ans[dep+]=row[i];
for(int j=R[i];j!=i;j=R[j])Delete(col[j]);
if(Dance(dep+))return true;
for(int j=L[i];j!=i;j=L[j])Resume(col[j]);
}
Resume(p);
return false;
}
}dlx; int main(){
while(scanf("%d%d",&n,&m)!=EOF){
dlx.Init(n,m);
for(int i=;i<=n;i++){
int k,x;
scanf("%d",&k);
while(k--){
scanf("%d",&x);
dlx.Link(i,x);
}
}if(!dlx.Dance())
printf("NO\n");
}
return ;
}