Dancing Links X 舞蹈链。
实质为用循环十字链在图上将所有“1”的位置链起来
构造较为巧妙,且极易理解,本题为 DLX 模板(精确覆盖问题)
DLX 算法的题目做法一般为将所求方案转化为行号,将限制条件转化为列号
然后 dfs 暴力枚举,用循环十字链优化
/*
Finished at 12:14 on 2024.4.5
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 510, M = 250510;
int n, m;
int a[N][N];
int row[M], col[M];
//row为每个点所在行号,col为每个点所在列号
int cnt, s[N], h[N];
//cnt为给每个链上的点的编号
//s表示某一列上所建链表点个数
//h为每一行的列表头
int u[M], d[M], l[M], r[M];
//u, d, l, r分别表示某个链表点上下左右所连的
int res[N];
//所选行号
void init() //初始化第0行的链表头
{
for (int i = 0; i <= m; i ++ )
u[i] = d[i] = i, l[i] = i - 1, r[i] = i + 1; //初始化左右,上下还没点,所以指向自己
l[0] = m, r[m] = 0, cnt = m; //处理剩下的0,m点
}
void link(int x, int y)
{
s[y] ++ ;
cnt ++ ;
row[cnt] = x, col[cnt] = y;
u[cnt] = y;
d[cnt] = d[y]; //可类比链表,正常加即可
u[d[y]] = cnt;
d[y] = cnt;
if (!h[x]) h[x] = l[cnt] = r[cnt] = cnt; //本行无链表点,则加进去
else
{
l[cnt] = l[h[x]];
r[cnt] = h[x]; //正常双向链表加
r[l[h[x]]] = cnt;
l[h[x]] = cnt;
}
}
void remove(int x)
{
r[l[x]] = r[x], l[r[x]] = l[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[col[j]] -- ;
}
void resume(int x)
{
r[l[x]] = x, l[r[x]] = 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[col[j]] ++ ;
}
bool dance(int depth)
{
if (r[0] == 0)
{
for (int i = 0; i < depth; i ++ ) cout << res[i] << ' ';
cout << '\n'; //第0行删完了
return true;
}
int y = r[0];
for (int i = r[0]; i; i = r[i]) //优先找1少的
if (s[y] > s[i]) y = i;
remove(y);
for (int i = d[y]; i != y; i = d[i])
{
res[depth] = row[i];
for (int j = r[i]; j != i; j = r[j]) remove(col[j]);
if (dance(depth + 1)) return true; //暴力枚举
for (int j = l[i]; j != i; j = l[j]) resume(col[j]);
}
resume(y);
return false;
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
cin >> a[i][j];
init();
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
if (a[i][j]) link(i, j); //1位置加点
if (!dance(0)) cout << "No Solution!\n";
return 0;
}
标签:Links,Dancing,int,链表,算法,col,row
From: https://www.cnblogs.com/MafuyuQWQ/p/18420316