hust 1017(Dancing Links模板题)

Exact cover

Special Judge
Time Limit: 
15 Sec   Memory Limit: 128 MB
Submissions: 3837   Solved: 2086

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

dupeng

题目:http://acm.hust.edu.cn/thanks/problem.php?id=1017

分析:做这题之前先看了一天都论文,纠结的没看懂。。。这理解能力阿~~~后来直接找个模板来不断都Debug。。。= =,终于搞懂了,还是代码通俗易懂阿!!!

整个算法可谓非常完美,从任何一个角度来看都是对称的先删除都后恢复,这句话很重要,否则会乱了原来都结构。。。这样导致RE了一次,囧。。。

下面这个代码就当作我的模板了,这回没有自己搞一个了,直接抄袭,然后改改~~~

代码:

#include<cstdio>
#define N 2011
#define M 102011
int U[M],D[M],L[M],R[M],C[M],X[M];
int H[N],S[N],Q[N];
int size,n,m;
void remove(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])
            U[D[j]]=U[j],D[U[j]]=D[j],--S[C[j]];
}
void resume(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[C[U[D[j]]=D[U[j]]=j]];
}
bool Dance(int k)
{
    int i,j,tmp,c;
    if(!R[0])
    {
        printf("%d",k);
        for(i=0; i<k; ++i)printf(" %d",X[Q[i]]);
        puts("");
        return 1;
    }
    for(tmp=N,i=R[0]; i; i=R[i])
        if(S[i]<tmp)tmp=S[c=i];
    remove(c);
    for(i=D[c]; i!=c; i=D[i])
    {
        Q[k]=i;
        for(j=R[i]; j!=i; j=R[j])remove(C[j]);
        if(Dance(k+1))return 1;
        for(j=L[i]; j!=i; j=L[j])resume(C[j]);
    }
    resume(c);
    return 0;
}
void Link(int r,int c)
{
    ++S[C[size]=c];
    D[size]=D[c];
    U[D[c]]=size;
    U[size]=c;
    D[c]=size;
    if(H[r]<0)H[r]=L[size]=R[size]=size;
    else
    {
        R[size]=R[H[r]];
        L[R[H[r]]]=size;
        L[size]=H[r];
        R[H[r]]=size;
    }
    X[size++]=r;
}
int main()
{
    int i,j,num;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        for(i=0; i<=m; ++i)
        {
            S[i]=0;
            D[i]=U[i]=i;
            L[i+1]=i;
            R[i]=i+1;
        }
        R[m]=0;
        size=m+1;
        for(i=1; i<=n; ++i)
        {
            H[i]=-1;
            scanf("%d",&num);
            while(num--)scanf("%d",&j),Link(i,j);
        }
        if(!Dance(0))puts("NO");
    }
    return 0;
}


你可能感兴趣的:(hust 1017(Dancing Links模板题))