舞蹈链(DLX)模板

· · 个人记录

#include<bits/stdc++.h>
using namespace std;
const int MaxN=2.6e4;
int n,m;
int U[MaxN],D[MaxN],L[MaxN],R[MaxN],row[MaxN],line[MaxN],first[MaxN],sizes[MaxN],id;
vector<int>ans;
inline void build(const int &r,const int &c){
    for(int i=0;i<=c;i++){
        L[i]=i-1;
        R[i]=i+1;
        U[i]=D[i]=i;
    }
    L[0]=c;
    R[c]=0;
    id=c;
}
inline void insert(const int &r,const int &c){
    id++;
    row[id]=r;
    line[id]=c;
    sizes[c]++;
    U[id]=c;
    D[id]=D[c];
    U[D[c]]=id;
    D[c]=id;
    if(!first[r]){
        first[r]=L[id]=R[id]=id;
    }else{
        L[id]=first[r];
        R[id]=R[first[r]];
        L[R[first[r]]]=id;
        R[first[r]]=id;
    }
}
inline void remove(const 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];
            sizes[line[j]]--;
        }
    }
}
inline void recover(const int &c){
    for(int i=U[c];i!=c;i=U[i]){
        for(int j=L[i];j!=i;j=L[j]){
            U[D[j]]=D[U[j]]=j;
            sizes[line[j]]++;
        }
    }
    L[R[c]]=R[L[c]]=c;
}
inline bool dance(int dep){
    int c=R[0];
    if(!c){
        return 1;
    }
    for(int i=R[0];i!=0;i=R[i]){
        if(sizes[i]<sizes[c]){
            c=i;
        }
    }
    remove(c);
    for(int i=D[c];i!=c;i=D[i]){
        ans.push_back(row[i]);
        for(int j=R[i];j!=i;j=R[j]){
            remove(line[j]);
        }
        if(dance(dep+1)){
            return 1;
        }
        for(int j=L[i];j!=i;j=L[j]){
            recover(line[j]);
        }
        ans.pop_back();
    }
    recover(c);
    return 0;
}
int main(){
    scanf("%d%d",&n,&m);
    build(n,m);
    for(int i=1,x;i<=n;i++){
        for(int j=1;j<=m;j++){
            scanf("%d",&x);
            if(x){
                insert(i,j);
            }
        }
    }
    if(!dance(1)){
        puts("No Solution!");
    }else{
        for(auto i:ans){
            printf("%d ",i);
        }
        puts("");
    }
    return 0;
}