(选出一些行使得这些行构成矩阵的每一列都有且只有一个1)
Original | Transformed |
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
Original | Transformed |
Yes, I found it It is impossible
题意:给出N行M列的1组成的矩阵,找出这样一个M列的子矩阵,它的每一列有且仅有一个'1'。
前言:对DFS没有清晰的掌握,很难做对这一题!
思路:
对于子矩阵每一列只能有一个'1',但是这个子矩阵的行起点以及列起点我们不知道,枚举的话也没办法处理其他列的行起点、列起点。我们设置一个done数组,如果某一列的一部分被选进子矩阵,那么这一列一定有一个'1'。我们称这个'1'为"被选中的1"。这时done数组值为1。如果暂时没有某个'1'被选中,done的值为0。
这其实也是一种对于状态的记录。姑且算是一种状态压缩吧。只关心当前搜索深度下,矩阵的该列有没有选中1个'1'。
(P.S. 一旦某行有一个'1'被选中,那么这一行所有的'1'都必须被选中)
从第0列开始dfs每一列。由于done数组的值在不同搜索深度下值是不一样的,回溯的时候又需要恢复done数组。因此我们在每层堆栈需要新建一个done_数组来暂存done数组的状态。以备恢复。
对于列m,遍历它的n行,找到一个'1',设该行为i,之后遍历m列看是否有冲突:
我们分类讨论一下:
①若 i 行和另一列k被选中的'1'不是同一行。这个时候通过done[k] & mat[i][k]我们可以轻易地得知k列出现了两个'1'位于同一个子矩阵中。
②若是处于同一行。根据某个'1'被选中那么该行所有'1'被选中,我们不需要枚举0~n,可以直接dfs下一列,因此需要控制这种情况不要出现。
在没有冲突的情况下,我们暂存done数组,并且选中i行的所有'1'。dfs下一层。然后恢复done数组。
P.S. 根据这一题可以发现,DFS不只是单纯的搜索,在搜索过程中需要摸清每一步应该是什么状态,状态应该如何表示,来进行合适的标记以及剪枝。
代码如下:
/**
* ID: j.sure.1
* PROG:
* LANG: C++
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <climits>
#include <iostream>
#define For(i, x, y) for(int i=x; i<y; i++)
#define For_(i, x, y) for(int i=x; i>=y; i--)
#define Mem(f, x) memset(f, x, sizeof(f))
#define Sca(x) scanf("%d", &x)
#define Pri(x) printf("%d\n", x)
#define LL long long
using namespace std;
const int INF = 0x3f3f3f3f;
/****************************************/
const int N = 333;
int mat[20][N], n, m;
bool ok, done[N];
void dfs(int u)
{
if(u == m) {
ok = 1;
return ;
}
if(done[u]) dfs(u+1);//Attention!When this column has been choose, you can't choose any other row
else For(i, 0, n) {
if(mat[i][u]) {//Choose i
bool fail = false;
For(j, 0, m) {
if(done[j] && mat[i][j]) {
fail = true; break;
}//any column done will crash the '1' of the same row that column
}
if(!fail) {
bool done_[N];//use global variable will get WA, 'cause every stack has a done_[], they are different
memcpy(done_, done, sizeof(done));//backup done[]
For(j, 0, m) {
if(mat[i][j]) done[j] = 1;
}//Attention!!!When U choose this row, every '1' of this row must be choose. Or U will get WA
dfs(u+1);
memcpy(done, done_, sizeof(done));//recover done[]
}
}
}
}
int main()
{
#ifdef J_Sure
freopen("000.in", "r", stdin);
freopen("999.out", "w", stdout);
#endif
while(~scanf("%d%d", &n, &m)) {
Mem(done, 0);
ok = false;
For(i, 0, n) {
For(j, 0, m) {
Sca(mat[i][j]);
}
}
dfs(0);
if(ok) puts("Yes, I found it");
else puts("It is impossible");
}
return 0;
}