十字交叉双向循环链表(dancing links)
POJ 3740 Easy Finding
题目:
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. 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.
Input
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. 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.
Output
For each test case, if you could find it output "Yes, I found it", otherwise output "It is impossible" per line. For each test case, if you could find it output "Yes, I found it", otherwise output "It is impossible" per line.
Sample Input
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
Sample Output
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 "); else printf("It is impossible "); } return 0; }
上一篇:
IDEA上Java项目控制台中文乱码