Easy Finding
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 18660 | Accepted: 5120 |
Description
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.
Output
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
Source
POJ Monthly Contest - 2009.08.23, MasterLuo
题意:给你一个01矩阵,问能不能选出一些行,使得每一列都有且仅在一行的那一列为1
解题思路:舞蹈链的精确覆盖
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cctype>
#include <map>
#include <cmath>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <functional>
using namespace std;
#define LL long long
const int INF = 0x3f3f3f3f;
const int maxn = 300005;
int n, m, a[20][400];
struct DLX
{
int L[maxn], R[maxn], U[maxn], D[maxn];
int row[maxn], col[maxn], ans[maxn], sum[maxn];
int n, m, num, cnt;
void add(int k, int l, int r, int u, int d, int x, int y)
{
L[k] = l; R[k] = r; U[k] = u;
D[k] = d; row[k] = x; col[k] = y;
}
void reset(int n, int m)
{
this->n = n; this->m = m;
for (int i = 0; i <= m; i++)
{
add(i, i - 1, i + 1, i, i, 0, i);
sum[i] = 0;
}
L[0] = m, R[m] = 0, cnt = m + 1;
}
void insert(int x, int y)
{
int temp = cnt - 1;
if (row[temp] != x)
{
add(cnt, cnt, cnt, U[y], y, x, y);
U[D[cnt]] = cnt; D[U[cnt]] = cnt;
}
else
{
add(cnt, temp, R[temp], U[y], y, x, y);
R[L[cnt]] = cnt; L[R[cnt]] = cnt;
U[D[cnt]] = cnt; D[U[cnt]] = cnt;
}
sum[y]++, cnt++;
}
void remove(int k)
{
R[L[k]] = R[k], L[R[k]] = L[k];
for (int i = D[k]; i != k; i = D[i])
for (int j = R[i]; j != i; j = R[j])
{
D[U[j]] = D[j];
U[D[j]] = U[j];
sum[col[j]]--;
}
}
void resume(int k)
{
R[L[k]] = k, L[R[k]] = k;
for (int i = D[k]; i != k; i = D[i])
for (int j = R[i]; j != i; j = R[j])
{
D[U[j]] = j;
U[D[j]] = j;
sum[col[j]]++;
}
}
bool dfs(int k)
{
if (!R[0]) { num = k; return true; }
int now = R[0];
for (int i = now; i != 0; i = R[i])
if (sum[now] > sum[i]) now = i;
remove(now);
for (int i = D[now]; i != now; i = D[i])
{
ans[k] = row[i];
for (int j = R[i]; j != i; j = R[j]) remove(col[j]);
if (dfs(k + 1)) return true;
for (int j = L[i]; j != i; j = L[j]) resume(col[j]);
}
resume(now);
return false;
}
}dlx;
int main()
{
while (~scanf("%d %d", &n, &m))
{
dlx.reset(n, m);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
scanf("%d", &a[i][j]);
if (a[i][j]) dlx.insert(i, j);
}
if (dlx.dfs(0)) printf("Yes, I found it\n");
else printf("It is impossible\n");
}
return 0;
}