天天看点

HUST 1017 Exact cover

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.

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".

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

3 2 4 6

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const ll maxn=100005;
int n,m,x,y;

inline void read(int &ret)
{
	char c;
	do { c = getchar();
	} while(c < '0' || c > '9');
	ret = c - '0';
	while((c=getchar()) >= '0' && c <= '9')
	ret = ret * 10 + ( c - '0' );
}

struct DLX
{
	int L[maxn],R[maxn],U[maxn],D[maxn];
	int row[maxn],col[maxn],ans[maxn],cnt[maxn];
	int n,m,num,sz;
	void add(int now,int l,int r,int u,int d,int x,int y)
	{
		L[now]=l;	R[now]=r;	U[now]=u;
		D[now]=d;   row[now]=x;  col[now]=y;
	}
	void reset(int n,int m)
	{
		this->n=n;	this->m=m;
		for (int i=0;i<=m;i++)
		{
			add(i,i-1,i+1,i,i,0,i);
			cnt[i]=0;
		}
		L[0]=m; 	R[m]=0; 	sz=m+1;
	}
	void insert(int x,int y)
	{
		int ft=sz-1;	
		if (row[ft]!=x)
		{
			add(sz,sz,sz,U[y],y,x,y);
			U[D[sz]]=sz; D[U[sz]]=sz;
		}
		else 
		{
			add(sz,ft,R[ft],U[y],y,x,y);
			R[L[sz]]=sz; L[R[sz]]=sz;
			U[D[sz]]=sz; D[U[sz]]=sz;
		}
		++cnt[y];	++sz;
	}
	void remove(int now)
	{
		R[L[now]]=R[now];
		L[R[now]]=L[now];
		for (int i=D[now];i!=now;i=D[i])
			for (int j=R[i];j!=i;j=R[j])
			{
				D[U[j]]=D[j];
				U[D[j]]=U[j];
				--cnt[col[j]];
			}
	}
	void resume(int now)
	{
		R[L[now]]=now;
		L[R[now]]=now;
		for (int i=D[now];i!=now;i=D[i])
			for (int j=R[i];j!=i;j=R[j])
			{
				D[U[j]]=j;
				U[D[j]]=j;
				++cnt[col[j]];
			}
	}
	bool dfs(int x)
	{
		if (!R[0]) {num=x; return true;}
		int now=R[0];
		for (int i=now;i!=0;i=R[i])
			if (cnt[now]>cnt[i]) now=i;
		remove(now);
		for (int i=D[now];i!=now;i=D[i])
		{
			ans[x]=row[i];
			for (int j=R[i];j!=i;j=R[j]) remove(col[j]);
			if (dfs(x+1)) return true;
			for (int j=R[i];j!=i;j=R[j]) resume(col[j]);
		}
		resume(now);
		return false;
	}
	void display()
	{
		printf("%d ",num);
		for (int i=0;i<num;++i) 
			printf("%d%s",ans[i],i==num-1?"\n":" ");
	}
}dlx;

int main()
{
	while (~scanf("%d%d",&n,&m))
	{
		dlx.reset(n,m);
		for (int i=1;i<=n;++i)
		{
			scanf("%d",&x);
			while (x--) {scanf("%d",&y); dlx.insert(i,y); }
		}
		if (dlx.dfs(0)) dlx.display();
		else printf("NO\n");
	}
	return 0;
}