Easy Finding
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 15738 | Accepted: 4177 |
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
题意:
给一个n*m的01矩阵,问能否找到k行,使得每一列刚好只有一行为1
Dancing links 点击打开链接
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <set>
using namespace std;
//#define WIN
#ifdef WIN
typedef __int64 LL;
#define iform "%I64d"
#define oform "%I64d\n"
#else
typedef long long LL;
#define iform "%lld"
#define oform "%lld\n"
#endif
#define S64I(a) scanf(iform, &(a))
#define P64I(a) printf(oform, (a))
#define REP(i, n) for(int (i)=0; (i)<n; (i)++)
#define REP1(i, n) for(int (i)=1; (i)<=(n); (i)++)
#define FOR(i, s, t) for(int (i)=(s); (i)<=(t); (i)++)
const int INF = 0x3f3f3f3f;
const double eps = 10e-9;
const double PI = (4.0*atan(1.0));
const int maxn = 6000 + 20;
int U[maxn], D[maxn], L[maxn], R[maxn], S[maxn];
int H[maxn];
int COL[maxn]; // 列号
int n, m;
int size;
void init() {
for(int i=0; i<=m; i++) {
U[i] = D[i] = i;
L[i] = i-1;
R[i] = i+1;
S[i] = 0;
}
R[m] = 0;
L[0] = m;
size = m+1;
memset(H, -1, sizeof(H));
}
void insert(int row, int col) {
U[size] = U[col];
D[size] = col;
D[U[col]] = size;
U[col] = size;
if(H[row] == -1) {
H[row] = R[size] = L[size] = size;
} else {
int rh = H[row];
R[size] = rh;
L[size] = L[rh];
R[L[rh]] = size;
L[rh] = size;
}
S[col]++;
COL[size] = col;
size++;
}
void remove(int c) {
L[R[c]] = L[c];
R[L[c]] = R[c];
for(int i=D[c]; i!=c; i=D[i]) {
for(int j=R[i]; j!=i; j=R[j]) {
S[COL[j]]--;
U[D[j]] = U[j];
D[U[j]] = D[j];
}
}
}
void resume(int c) {
L[R[c]] = c;
R[L[c]] = c;
for(int i=D[c]; i!=c; i=D[i]) {
for(int j=L[i]; j!=i; j=L[j]) {
S[COL[j]]++;
U[D[j]] = j;
D[U[j]] = j;
}
}
}
bool dfs() {
if(R[0] == 0) {
return true;
}
int c = R[0];
int mins = S[c];
for(int i=R[0]; i!=0; i=R[i]) if(S[i] < mins) {
c = i;
mins = S[i];
}
remove(c);
for(int i=D[c]; i!=c; i=D[i]) {
for(int j=R[i]; j!=i; j=R[j]) remove(COL[j]);
if(dfs()) return true;
for(int j=L[i]; j!=i; j=L[j]) resume(COL[j]);
}
resume(c);
return false;
}
int main() {
while(scanf("%d%d", &n, &m) != EOF) {
init();
REP1(i, n) REP1(j, m) {
int t;
scanf("%d", &t);
if(t) insert(i, j);
}
if(dfs()) {
puts("Yes, I found it");
} else {
puts("It is impossible");
}
}
return 0;
}