题目链锁 : http://poj.org/problem?id=1681 #include #include #include #include #include #include #include #include #include #include using namespace std; #define inf 0x3f3f3f3f #define eps 1e-9 #define mod 100007 #define FOR(i,s,t) for(int i = s; i < t; ++i ) #define REP(i,s,t) for( int i = s; i <= t; ++i ) #define LL long long #define ULL unsigned long long #define pii pair #define MP make_pair #define lson id << 1 , l , m #define rson id << 1 | 1 , m + 1 , r #define maxn ( 100000+10 ) #define maxe ( 20000+10 ) int a[333][333]; int x[333]; int free_x[333], free_num; int gauss ( int var, int equ ) { int max_r, col, k; free_num = 0; for( k = 0, col = 0; k < equ && col < var; ++col, ++k ) { max_r = k; for( int i = k+1; i < equ; ++i ) { if( a[i][col] > a[max_r][col] ) max_r = i; } if( a[max_r][col] == 0 ) { free_x[free_num++] = col; --k; continue; } if( max_r != k ) { for( int j = col; j < var+1; ++j ) swap( a[k][j], a[max_r][j] ); } for( int i = k+1; i < equ ; ++i ) { if( a[i][col] ) for( int j = col;j < var+1; ++j ) a[i][j] ^= a[k][j] ; } } for( int i = k; i < equ; ++i ) { if( a[i][col] != 0 ) return -1; } if( var > k ) return var - k; for( int i = var - 1; i >= 0; -- i ) { x[i] = a[i][var]; for( int j = i+1; j < var; ++j ) { x[i] ^= ( a[i][j] && x[j] ); } } return 0; } char G[33][33]; int main () { int T; int cas = 1; scanf("%d", &T ) ; while( T-- ) { int n; scanf("%d", &n ); for( int i = 0; i < n; ++i ) scanf("%s", G[i] ); memset( a, 0, sizeof( a ) ); memset( x, 0, sizeof( x ) ); int m = n * n; for( int i = 0; i < n; ++i ) for( int j = 0; j < n; ++j ) if( G[i][j] == 'y' ) a[i * n + j][m] = 0; else a[i* n + j][m] = 1; for( int i = 0; i < n; ++i ) for( int j = 0; j < n; ++j ) { int t = i * n + j; a[t][t] = 1; if( i > 0 ) a[t-n][t] = 1; if( i < n-1 ) a[t+n][t] = 1; if( j > 0 ) a[t-1][t] = 1; if( j < n-1 ) a[t+1][t] = 1; } int ans = gauss( m, m ); if( ans == -1 ) { puts("inf" ); } else if( ans == 0 ) { int res = 0; for( int i = 0; i < m; ++i ) res += x[i]; printf("%d\n", res ); } else { //枚举自由变元 int tot = ( 1 << ans ); int res = inf; for( int i = 0; i < tot; ++i ) { int cnt = 0; for( int j = 0; j < ans; ++j ) { if( ( 1 << j ) & i ) x[free_x[j]] = 1, ++cnt; else x[free_x[j]] = 0; } //how ? for( int j = m - 1 - ans; j >= 0; --j ) { int id; for( id = j; id < m; ++id ) if( a[j][id] ) break; x[id] = a[j][m]; for( int k = id + 1; k < m; ++k ) if( a[j][k] ) x[id] ^= x[k]; cnt += x[id]; } res = min ( res, cnt ); } printf("%d\n", res ); } } }