有N个相同的开关,每个开关都与某些开关有着联系,每当你打开或者关闭某个开关的时候,其他的与此开关相关联的开关也会相应地发生变化,即这些相联系的开关的状态如果原来为开就变为关,如果为关就变为开。
你的目标是经过若干次开关操作后使得最后N个开关达到一个特定的状态。
对于任意一个开关,最多只能进行一次开关操作。
你的任务是,计算有多少种可以达到指定状态的方法。(不计开关操作的顺序)
输入格式
输入第一行有一个数K,表示以下有K组测试数据。
每组测试数据的格式如下:
第一行 一个数N(0 < N < 29)。
第二行 N个0或者1的数,表示开始时N个开关状态。
第三行 N个0或者1的数,表示操作结束后N个开关的状态。
接下来 每行两个数I J,表示如果操作第 I 个开关,第J个开关的状态也会变化。
每组数据以 0 0 结束。
输出格式
如果有可行方法,输出总数,否则输出Oh,it’s impossible~!! 。
输入样例:
2
3
0 0 0
1 1 1
1 2
1 3
2 1
2 3
3 1
3 2
0 0
3
0 0 0
1 0 1
1 2
2 1
0 0
输出样例:
4
Oh,it’s impossible~!!
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 35;
int n;
int a[N][N];
int gauss(){
int r, c;
for (r = 1, c = 1; c <= n; c ++){
int t = r;
for (int i = r + 1; i <= n ; i ++)
if (a[i][c])
t = i;
if (!a[t][c]) continue;
for (int i = c; i <= n + 1 ; i ++) swap(a[t][i], a[r][i]);
for (int i = r + 1; i <= n; i ++)
for (int j = n + 1; j >= c; j --)
a[i][j] ^= a[i][c] & a[r][j];
r ++;
}
int res = 1;
if (r < n + 1){
for (int i = r; i <= n; i ++){
if (a[i][n + 1]) return -1;
res *= 2;
}
}
return res;
}
int main(){
int T;
scanf("%d", &T);
while(T -- ){
memset(a, 0, sizeof a);
scanf("%d", &n);
for (int i = 1; i <= n; i ++) scanf("%d", &a[i][n + 1]);
for (int i = 1; i <= n; i ++){
int t ;
scanf("%d", &t);
a[i][n + 1] ^= t;
a[i][i] = 1;
}
int x, y;
while(scanf("%d%d", &x, &y) , x || y) a[y][x] = 1;
int t = gauss();
if (t == -1) puts("Oh,it's impossible~!!");
else printf("%d\n", t);
}
return 0;
}