P6126 题解

· · 题解

挺有意思的题!

发现一只鸟只有在上游或者下游两种状态,考虑分别设成 1 和 0。

仅仅说有偶数的朋友在一起是不好做的,把一只鸟的朋友个数按照奇偶分类:

现在我们得到了有关奇偶性的一些方程组,显然可以用高斯消元解异或方程组!

无解直接用高斯消元判就可以了,无解的条件是等式左边的系数全为零且右边非零。

高斯消元中会出现全行异或的情况,可以用 std :: bitset。

Code

#include <bits/stdc++.h>
#define f(i ,m ,n ,x) for (int i = (m) ; i <= (n) ; i += (x))

template < typename T > inline void read ( T &x ) {
    x = 0 ;
    bool flag (0) ; char ch = getchar () ;
    while (! isdigit (ch)) {
        flag = ch == '-' ;
        ch = getchar () ;
    } while (isdigit (ch)) {
        x = (x << 1) + (x << 3) + (ch ^ 48) ;
        ch = getchar () ;
    } flag ? x = - x : 0 ;
}

const int N = 2007 ;
int n ,ans[N] ,tot ;
bool use[N] ;
std :: bitset < N > x[N] ;

inline void gauss () {
    f (i ,1 ,n ,1) {
        int cur = 1 ;
        for ( ; cur <= n && (x[cur][i] != 1 || use[cur]) ; cur ++) ;
        if (cur == n + 1) continue ;
        use[i] = true ;
        std :: swap (x[cur] ,x[i]) ; 
        f (j ,1 ,n ,1) 
            if (x[j][i] && j != i) x[j] ^= x[i] ;
    }
}

int main () {
    read (n) ;
    f (i ,1 ,n ,1) {
        int m ; read (m) ;
        if (m & 1) {
            f (j ,1 ,m ,1) {
                int a ; read (a) ;
                x[i][a] = true ;
            } x[i][i] = true ;
            x[i][n + 1] = true ;
        } else {
            f (j ,1 ,m ,1) {
                int a ; read (a) ;
                x[i][a] = true ;
            }
        }
    } gauss () ;
    f (i ,1 ,n ,1) {
        int cur = 1 ;
        for ( ; cur <= n + 1 && x[i][cur] == 0 ; cur ++) ;
        if (cur == n + 1) return puts ("Impossible") ,0 ;
    } f (i ,1 ,n ,1) {
        if (! use[i]) continue ;
        if (x[i][n + 1]) ans[++ tot] = i ;
    } std :: cout << tot << '\n' ;
    f (i ,1 ,tot ,1) std :: cout << ans[i] << ' ' ; puts ("") ;
    return 0 ;
}