Time Limit:15000MS | Memory Limit:131072KB | 64bit IO Format:%lld & %llu |
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
Source
人生第一道DLX,debug好艰难,经过无数的wa之后,终于找到了错误。
代码:
#pragma comment(linker, "/STACK:102400000,102400000")
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <string>
#include <time.h>
#include <math.h>
#include <queue>
#include <stack>
#include <set>
#include <map>
using namespace std;
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
typedef long long ll;
struct DLX{
const static int maxn=2100*2100;
int L[maxn],R[maxn],U[maxn],D[maxn];
int ans[maxn],size,cnt,row[maxn],col[maxn],S[maxn],H[maxn];
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],--S[col[j]];
}
void add(int c){
R[L[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])
++S[col[U[D[j]]=D[U[j]]=j]];
}
void init(int m){
for(int i=0;i<=m;i++){
S[i]=0;
L[i]=i-1;
R[i]=i+1;
U[i]=D[i]=i;
}
L[0]=m;R[m]=0;
size=m+1;
memset(H,-1,sizeof(H));
}
void link(int x,int y){
++S[col[size]=y];
row[size]=x;
D[size]=D[y];
U[D[y]]=size;
U[size]=y;
D[y]=size;
if(H[x]<0)H[x]=L[size]=R[size]=size;
else {
R[size]=R[H[x]];
L[R[H[x]]]=size;
L[size]=H[x];
R[H[x]]=size;
}
size++;
}
bool dfs(int k){
if(!R[0]){
cnt=k;
return 1;
}
int c=R[0];for(int i=R[0];i;i=R[i])if(S[c]>S[i])c=i;
del(c);
for(int i=D[c];i!=c;i=D[i]){
for(int j=R[i];j!=i;j=R[j])del(col[j]);
ans[k]=row[i];
if(dfs(k+1))return true;
for(int j=L[i];j!=i;j=L[j])add(col[j]);
}
add(c);
return 0;
}
}dlx;
int n,m;
int main()
{
//freopen("data.in","r",stdin);
//freopen("data.out","w",stdout);
while(cin>>n>>m){
dlx.init(m);
for(int i=1;i<=n;i++){
int num,col;
cin>>num;
while(num--){
cin>>col;
dlx.link(i,col);
}
}
if(dlx.dfs(0)){
printf("%d",dlx.cnt);
for(int i=0;i<dlx.cnt;i++)
printf(" %d",dlx.ans[i]);
puts("");
}
else puts("NO");
}
return 0;
}