poj3740 Easy Finding(深搜)

来源:互联网 发布:苹果办公软件 编辑:程序博客网 时间:2024/06/04 23:35
 
Easy Finding
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 11432 Accepted: 2802

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 30 1 00 0 11 0 04 40 0 0 11 0 0 01 1 0 10 1 0 0

Sample Output

Yes, I found itIt is impossible

 

 题意 :   给出一个0,1矩阵,一个新矩阵由该矩阵中的若干行组成,问是否存在这样的新矩阵满足每列有且仅有一个1

 

这题深搜加一点简单剪枝水过了,跳舞链有待学习

#include <iostream>using namespace std;// 对象int M, N; // 行,列int m[16][300]; // 原矩阵int v[300];   // 压缩向量bool zIndex[16]; // 标记全0行// 函数bool Clash( const int row ){for( int i = 0; i < N; ++ i )if( v[i] == 1 && m[row][i] == 1 )return true; // 冲突return false;}void GetAllZeroRowIndex(){memset( zIndex, false, sizeof(zIndex) );for( int i = 0; i < M; ++ i ) {bool flag = true;for( int j = 0; j < N; ++ j ) {if( m[i][j] == 1 ) {flag = false;break;}}if( flag ) zIndex[i] = true; // 标记全0行}}bool Full(){for( int i = 0; i < N; ++ i )if( v[i] == 0 )return false; // 压缩向量未满return true;}/**  深搜, 将第row行加入子矩阵*/bool DFS( const int row ){// 该行可选if( !zIndex[row] && !::Clash(row) ) {for( int i = 0; i < N; ++ i )v[i] = v[i] | m[row][i];if( ::Full() )return true;}else // 该行不可选return false;// 深搜子问题for( int i = row + 1; i < M; ++ i )if( ::DFS(i) )return true;// 该行不可行for( int i = 0; i < N; ++ i )v[i] = v[i] ^ m[row][i];return false;}// 优化bool HasColumnAllZero(){for( int i = 0; i < N; ++ i ) {bool flag = true;for( int j = 0; j < M; ++ j ) {if( m[j][i] != 0 ) {flag = false;break;}}if( flag ) return true; // 存在全0列}return false;}bool HasRowAllOne(){for( int i = 0; i < M; ++ i ) {bool flag = true;for( int j = 0; j < N; ++ j ) {if( m[i][j] != 1 ) {flag = false;break;}}if( flag ) return true; // 存在全1行}return false;}int main(){while( scanf( "%d%d", & M, & N ) == 2 ) {for( int i = 0; i < M; ++ i )for( int j = 0; j < N; ++ j )scanf( "%d", & m[i][j] );bool succ = false;if( ::HasColumnAllZero() ) succ = false;else if( ::HasRowAllOne() ) succ = true;else {// 标记全0行::GetAllZeroRowIndex();memset( v, 0, sizeof(v) );for( int i = 0; i < M; ++ i )if( ::DFS(i) ) {succ = true;break;}}if( succ ) printf( "Yes, I found it\n" );else printf( "It is impossible\n" );}system( "pause" );return 0;}


 

 

原创粉丝点击