舞蹈链DLX算法
作者:互联网
常数与希望编织的一缕奇迹
模板
DLX算法全称:Dancing Line X算法。
X算法的意思就是不知道是哪种搜索算法,
而Dancing Line的意思就是用Dancing Line优化X算法。
Dancing Line是使用在类二维矩阵中的双向循环链表群。
上面的话可以意会
Dancing Line
其实就是对于每个元素,和它左边的第一个,右边的第一个,上边的,下边的,都连上双向指针。
如果左边没有,就循环着连到最右边,
上下右同理。
并且对于每一列设立一个头元素至于列的最上方。
那么删除一列的时候,直接删除头元素的左右指针。
删除一行的时候,删除每个元素的上下指针。
考虑恢复操作。
对于一般的双向链表(不会的看代码),按删除顺序反着恢复就可以了。
这个也是反着恢复就可以了。。。(具体实现短的巧妙)
这个X算法是来解决精确覆盖问题的。
精确覆盖是指用几个集合不重不漏的覆盖所有元素。
每次选择被最少的集合包括的元素(删一列),然后枚举选哪个集合(删一行),把这个集合包括的元素都删完(删很多列),然后继续搜,回溯时恢复。
具体看代码:
#include<bits/stdc++.h>
#define maxn 100005
#define maxpt 10005
using namespace std;
int n,m,rt;
int cnt,l[maxn],r[maxn],u[maxn],d[maxn],s[maxn],ans[maxn],tp[maxn],col[maxn];
void rem(int x){
l[r[x]] = l[x] , r[l[x]] = r[x];
for(int i=d[x];i!=x;i=d[i])
for(int j=r[i];j!=i;j=r[j])
u[d[j]] = u[j] , d[u[j]] = d[j] , s[tp[j]] --;
}
void rec(int x){
for(int i=u[x];i!=x;i=u[i])
for(int j=l[i];j!=i;j=l[j])
u[d[j]] = j , d[u[j]] = j , s[tp[j]] ++;
l[r[x]] = x , r[l[x]] = x;
}
int dfs(int dep){
if(r[rt] == rt) return dep;
int loc = r[rt];
for(int i=r[rt];i!=rt;i=r[i]) if(s[i] < s[loc]) loc = i;
if(!s[loc]) return -1;
rem(loc);
for(int i=d[loc],ret;i!=loc;i=d[i]){
for(int j=r[i];j!=i;j=r[j]) rem(tp[j]);
ans[dep] = col[i];
if((ret = dfs(dep+1))!=-1) return ret;
for(int j=l[i];j!=i;j=l[j]) rec(tp[j]);
}
rec(loc);
return -1;
}
int main(){
scanf("%d%d",&n,&m);
rt = ++cnt;
l[1] = r[1] = u[1] = d[1] = 1;
for(int i=1;i<=m;i++){
++cnt;
u[cnt] = d[cnt] = l[r[cnt] = 1] = r[l[cnt] = cnt - 1] = cnt;
}
for(int i=1;i<=n;i++)
for(int j=1,hd=0;j<=m;j++){
int x;scanf("%d",&x);
if(x){
s[tp[++cnt] = j+1]++;
col[cnt] = i;
if(hd) l[r[cnt] = hd] = r[l[cnt] = cnt - 1] = cnt;
else{
hd = cnt;
r[cnt] = l[cnt] = hd;
}
int tmp = u[j+1];
u[d[cnt] = j+1] = d[u[cnt] = tmp] = cnt;
}
}
int ret = dfs(0);
if(ret == -1) puts("No Solution!");
else{
for(int i=0;i<ret;i++)
printf("%d%c",ans[i],i==ret-1?'\n':' ');
}
}
标签:rt,loc,Dancing,int,舞蹈,算法,maxn,Line,DLX 来源: https://blog.csdn.net/qq_35950004/article/details/91388313