您的位置:首页 > 其它

hust 1017 dancing links 模板题

2014-10-15 19:45 405 查看


1017 - Exact cover

Time Limit: 15s Memory
Limit: 128MB

Special Judge Submissions:
5878 Solved: 3104

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


HINT

SOURCE
#include<stdio.h>
#define N 1000005
int s
,l
,r
,u
,d
,row
,col
,h
,len,ans
,size;
//初始化
void init(int n,int m)
{
int i;
for(i=0;i<=m;i++)
{
s[i]=0;//记录第i列中1的个数
u[i]=d[i]=i;//上下
l[i]=i-1;//左
r[i]=i+1;//右
}
r[m]=0; l[0]=m;
size=m;
for(i=1;i<=n;i++)
h[i]=-1;
}
//插入
void link(int x,int y)
{
++s[col[++size]=y];
row[size]=x;
d[u[y]]=size;//纵向插入
u[size]=u[y];
d[size]=y;
u[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;
}
}
//移除
void remove(int c)
{
int i,j;
l[r[c]]=l[c];
r[l[c]]=r[c];
for(i=d[c];i!=c;i=d[i])
for(j=r[i];j!=i;j=r[j])
{
u[d[j]]=u[j];
d[u[j]]=d[j];
--s[col[j]];
}
}
//恢复
void resume(int c)
{
int i,j;
l[r[c]]=r[l[c]]=c;
for(i=d[c];i!=c;i=d[i])
for(j=r[i];j!=i;j=r[j])
{
d[u[j]]=j;
u[d[j]]=j;
++s[col[j]];
}
}
bool dance(int x)
{
int i,j;
if(r[0]==0)
{
len=x;
return true;
}
int c=r[0];
for(i=r[0];i!=0;i=r[i])
if(s[i]<s[c])
c=i;
remove(c);
for(i=d[c];i!=c;i=d[i])
{
ans[x]=row[i];
for(j=r[i];j!=i;j=r[j])
remove(col[j]);
if(dance(x+1)==true)
return true;
for(j=r[i];j!=i;j=r[j])
resume(col[j]);
}
resume(c);
return false;
}
int main()
{
int n,m,i,j,num;
while(scanf("%d%d",&n,&m)!=EOF)
{
init(n,m);
for(i=1;i<=n;i++)
{
scanf("%d",&num);
while(num--)
{
scanf("%d",&j);
link(i,j);
}
}
if(dance(0)==false)
printf("NO\n");
else
{
printf("%d",len);
for(i=0;i<len;i++)
printf(" %d",ans[i]);
printf("\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: