有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~!!

提示 提示 第一组数据的说明: 一共以下四种方法: 操作开关1 操作开关2 操作开关3 操作开关1、2、3 (不记顺序) C++内容:#include #include using namespace std;

// 计算总数 int count = 0;

// 检查开关状态是否与目标状态一致 bool check(vector& state, vector& target) { for (int i = 0; i < state.size(); i++) { if (state[i] != target[i]) { return false; } } return true; }

// 递归函数,尝试所有开关的状态 void dfs(vector& state, vector& target, vector<vector>& switches, int index) { // 如果已经检查到最后一个开关,检查状态是否与目标状态一致 if (index == state.size()) { if (check(state, target)) { count++; } return; }

// 不操作当前开关
dfs(state, target, switches, index + 1);

// 操作当前开关
state[index] = 1 - state[index];  // 翻转开关状态
for (int i = 0; i < switches[index].size(); i++) {
    int switchIndex = switches[index][i];
    state[switchIndex] = 1 - state[switchIndex];  // 翻转与当前开关相关联的开关状态
}
dfs(state, target, switches, index + 1);
// 恢复状态
state[index] = 1 - state[index];
for (int i = 0; i < switches[index].size(); i++) {
    int switchIndex = switches[index][i];
    state[switchIndex] = 1 - state[switchIndex];
}

}

int main() { int K; cin >> K; while (K--) { int N; cin >> N; vector start(N); vector target(N); for (int i = 0; i < N; i++) { cin >> start[i]; } for (int i = 0; i < N; i++) { cin >> target[i]; } vector<vector> switches(N); int I, J; cin >> I >> J; while (I != 0 && J != 0) { switches[I - 1].push_back(J - 1); cin >> I >> J; }

    count = 0;
    dfs(start, target, switches, 0);
    
    if (count == 0) {
        cout << "Oh,it's impossible~!!" << endl;
    } else {
        cout << count << endl;
    }
}

return 0;

原文地址: https://www.cveoy.top/t/topic/pifY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录