传送门:【POJ】3740 Easy Finding
题目分析:Dancing Links 模板题。
代码如下:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std ; #define REP( i , a , b ) for ( int i = a ; i < b ; ++ i ) #define REV( i , a , b ) for ( int i = a - 1 ; i >= b ; -- i ) #define FOR( i , a , b ) for ( int i = a ; i <= b ; ++ i ) #define FOV( i , a , b ) for ( int i = a ; i >= b ; -- i ) #define REC( i , A , o ) for ( int i = A[o] ; i != o ; i = A[i] ) #define CLR( a , x ) memset ( a , x , sizeof a ) const int MAXN = 305 ; const int MAXNODE = 5000 ; struct DLX { int L[MAXNODE] , R[MAXNODE] , U[MAXNODE] , D[MAXNODE] ; int row[MAXNODE] , col[MAXNODE] ; int S[MAXN] , H[MAXN] ; int deep , ans[MAXN] ; int size ; int n , m ; void remove ( int c ) { L[R[c]] = L[c] ; R[L[c]] = R[c] ; REC ( i , D , c ) REC ( j , R , i ) { U[D[j]] = U[j] ; D[U[j]] = D[j] ; -- S[col[j]] ; } } void resume ( int c ) { REC ( i , U , c ) REC ( j , L , i ) { ++ S[col[j]] ; D[U[j]] = j ; U[D[j]] = j ; } R[L[c]] = c ; L[R[c]] = c ; } int dance ( int d ) { if ( R[0] == 0 ) { deep = d ; return 1 ; } int c = R[0] ; REC ( i , R , 0 ) if ( S[c] > S[i] ) c = i ; remove ( c ) ; REC ( i , D , c ) { ans[d] = row[i] ; REC ( j , R , i ) remove ( col[j] ) ; if ( dance ( d + 1 ) ) return 1 ; REC ( j , L , i ) resume ( col[j] ) ; } resume ( c ) ; return 0 ; } void link ( int r , int c ) { ++ size ; row[size] = r ; col[size] = c ; ++ S[c] ; U[size] = U[c] ; D[size] = c ; D[U[c]] = size ; U[c] = size ; if ( ~H[r] ) { R[size] = H[r] ; L[size] = L[H[r]] ; L[R[size]] = size ; R[L[size]] = size ; } else H[r] = L[size] = R[size] = size ; } void init () { CLR ( H , -1 ) ; FOR ( i , 0 , n ) { R[i] = i + 1 ; L[i] = i - 1 ; U[i] = i ; D[i] = i ; } R[n] = 0 ; L[0] = n ; size = n ; } int read () { char c = ' ' ; while ( c < '0' || c > '9' ) c = getchar () ; int x = c - '0' ; getchar () ; return x ; } void input () { FOR ( i , 1 , m ) FOR ( j , 1 , n ) if ( read () ) link ( i , j ) ; } void solve () { init () ; input () ; if ( dance ( 0 ) ) printf ( "Yes, I found it\n" ) ; else printf ( "It is impossible\n" ) ; } } dlx ; int main () { while ( ~scanf ( "%d%d" , &dlx.m , &dlx.n ) ) dlx.solve () ; return 0 ; }