DLX的模板题。精确覆盖问题。
给你一个01矩阵,现在选择几行,是每列有且只有一个1.
操作过程不难理解。。就是建图坑了一会。。这次吃了大亏了
Easy Finding
| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 14686 | Accepted: 3841 |
Description
Given a M×N matrix A. Aij ∈ {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
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
#define MAXN 350*30+30
#define INF 0xFFFFFF
int head,sz;
int U[MAXN],D[MAXN],L[MAXN],R[MAXN];
int H[MAXN],ROW[MAXN],C[MAXN],S[MAXN],O[MAXN];
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])
{
U[D[j]]=U[j];
D[U[j]]=D[j];
--S[C[j]];
}
}
}
void resume(int c)
{
for(int i=U[c];i!=c;i=U[i])
{
for(int j=L[i];j!=i;j=L[j])
{
++S[C[j]];
U[D[j]]=j;
D[U[j]]=j;
}
}
L[R[c]]=c;
R[L[c]]=c;
}
bool dfs(int k)
{
if(R[head]==head)
return true;
int s=INF,c;
for (int t=R[head];t!=head;t=R[t])
{
if (S[t]<s)
{
s=S[t];
c=t;
}
}
remove(c);
for(int i=D[c];i!=c;i=D[i])
{
O[k]=i;
for(int j=R[i];j!=i;j=R[j])
remove(C[j]);
if(dfs(k+1))
return true;
for(int j=L[i];j!=i;j=L[j])
resume(C[j]);
}
resume(c);
return false;
}
void initDL(int n)
{
head=0;
for(int i=0;i<=n;i++)
{
U[i]=i;D[i]=i;
L[i]=i-1;R[i]=i+1;
S[i]=0;
}
R[n]=0;L[0]=n;S[0]=INF+1;
sz=n+1;
memset(H,0,sizeof(H));
}
void insert(int i, int j)
{
if(H[i])
{
L[sz] = L[H[i]];
R[sz] = H[i];
L[R[sz]] = sz;
R[L[sz]] = sz;
}
else
{
L[sz] = sz;
R[sz] = sz;
H[i] = sz;
}
U[sz] = U[j];
D[sz] = j;
U[D[sz]] = sz;
D[U[sz]] = sz;
C[sz] = j;
ROW[sz] = i;
++S[j];
++sz;
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
initDL(m);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
int x;
scanf("%d",&x);
if(x)
insert(i,j);
}
}
if(dfs(0))
printf("Yes, I found it\n");
else
printf("It is impossible\n");
}
return 0;
}
374

被折叠的 条评论
为什么被折叠?



