Easy Finding POJ - 3740(十字交叉双向循环链表dancing links)
【摘要】
题目:
Given a
M×
N matrix
A.
A
ij ∈ {0, 1} (0 ≤ i < M, 0 ≤ j < N), could you find some rows that let every cloumn con...
题目:
Given a M× N matrix A. A ij ∈ {0, 1} (0 ≤ i < M, 0 ≤ j < N), could you find some rows that let every cloumn contains and only contains one 1.
There are multiple cases ended by EOF. Test case up to 500.The first line of input is M, N ( M ≤ 16, N ≤ 300). The next M lines every line contains N integers separated by space.
For each test case, if you could find it output "Yes, I found it", otherwise output "It is impossible" per line.
3 3 0 1 0 0 0 1 1 0 0 4 4 0 0 0 1 1 0 0 0 1 1 0 1 0 1 0 0
Yes, I found it It is impossible
单纯的精确覆盖问题,用来作为学习dancing links的第一个题目再合适不过了。
代码:
-
#include<iostream>
-
#include<stdio.h>
-
using namespace std;
-
-
int m, n, num[17][301];
-
const int maxx = 6000, mr = 17;
-
int key, up[maxx], down[maxx], lef[maxx], rig[maxx];//上下左右
-
int row[maxx], col[maxx], rhead[mr];//行,列,每行第一个元素
-
-
void init()
-
{
-
for (int i = 0; i <= n; i++)
-
{
-
up[i] = i, down[i] = i;
-
lef[i] = i - 1, rig[i] = i + 1;
-
row[i] = 0, col[i] = i;
-
}
-
lef[0] = n, rig[n] = 0;
-
key = n;
-
for (int i = 0; i <= m; i++)rhead[i] = 0;
-
}
-
-
void push(int r, int c)//新增坐标在(r,c)的一个节点
-
{
-
row[++key] = r, col[key] = c;
-
up[key] = c, down[key] = down[c];
-
up[down[c]] = key, down[c] = key;
-
if (rhead[r] == 0)rhead[r] = lef[key] = rig[key] = key;
-
else
-
{
-
lef[key] = rhead[r], rig[key] = rig[rhead[r]];
-
lef[rig[rhead[r]]] = key, rig[rhead[r]] = key;
-
}
-
}
-
-
void del(int c)//删除第c列的所有元素和他们所在行的所有元素
-
{
-
lef[rig[c]] = lef[c], rig[lef[c]] = rig[c];
-
for (int i = down[c]; i != c; i = down[i])
-
for (int j = rig[i]; j != i; j = rig[j])
-
down[up[j]] = down[j], up[down[j]] = up[j];
-
}
-
-
void reback(int c)
-
{
-
lef[rig[c]] = rig[lef[c]] = c;
-
for (int i = down[c]; i != c; i = down[i])
-
for (int j = rig[i]; j != i; j = rig[j])
-
down[up[j]] = up[down[j]] = j;
-
}
-
-
bool dfs()
-
{
-
if (rig[0] == 0)return true;
-
int c = rig[0];
-
del(c);
-
for (int i = down[c]; i != c; i = down[i])
-
{
-
for (int j = rig[i]; j != i; j = rig[j])del(col[j]);
-
if (dfs())return true;
-
for (int j = rig[i]; j != i; j = rig[j])reback(col[j]);
-
}
-
reback(c);
-
return false;
-
}
-
-
int main()
-
{
-
while (scanf("%d%d",&m,&n)!=EOF)
-
{
-
init();
-
for (int i = 1; i <= m; i++)for (int j = 1; j <= n; j++)
-
{
-
scanf("%d", &num[i][j]);
-
if (num[i][j])push(i, j);
-
}
-
if (dfs())printf("Yes, I found it\n");
-
else printf("It is impossible\n");
-
}
-
return 0;
-
}
文章来源: blog.csdn.net,作者:csuzhucong,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/nameofcsdn/article/details/79890911
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)