fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int n, m;
  6. cin >> n >> m;
  7.  
  8. vector<int> initial(n);
  9. int init_state = 0;
  10. for (int i = 0; i < n; i++) {
  11. cin >> initial[i];
  12. init_state |= (initial[i] << i);
  13. }
  14.  
  15. // 预计算每个开关的影响掩码
  16. vector<int> effect(n, 0);
  17. for (int i = 0; i < n; i++) {
  18. effect[i] = (1 << i); // 影响自己
  19. }
  20.  
  21. for (int i = 0; i < m; i++) {
  22. int x, y;
  23. cin >> x >> y;
  24. x--; y--;
  25. effect[x] |= (1 << y);
  26. }
  27.  
  28. // BFS
  29. queue<pair<int, int>> q; // (state, switches_used)
  30. map<int, int> visited; // state -> switches_used (bitmask)
  31.  
  32. q.push({init_state, 0});
  33. visited[init_state] = 0;
  34.  
  35. while (!q.empty()) {
  36. auto [state, switches] = q.front();
  37. q.pop();
  38.  
  39. if (state == 0) {
  40. // 找到解,提取开关序号
  41. vector<int> result;
  42. for (int i = 0; i < n; i++) {
  43. if (switches & (1 << i)) {
  44. result.push_back(i + 1);
  45. }
  46. }
  47. for (int i = 0; i < result.size(); i++) {
  48. if (i > 0) cout << " ";
  49. cout << result[i];
  50. }
  51. cout << endl;
  52. return 0;
  53. }
  54.  
  55. // 尝试按每个未按过的开关
  56. for (int i = 0; i < n; i++) {
  57. if (!(switches & (1 << i))) {
  58. int new_state = state ^ effect[i];
  59. int new_switches = switches | (1 << i);
  60.  
  61. if (visited.find(new_state) == visited.end() ||
  62. __builtin_popcount(new_switches) < __builtin_popcount(visited[new_state]) ||
  63. (__builtin_popcount(new_switches) == __builtin_popcount(visited[new_state]) &&
  64. new_switches < visited[new_state])) {
  65. visited[new_state] = new_switches;
  66. q.push({new_state, new_switches});
  67. }
  68. }
  69. }
  70. }
  71.  
  72. cout << -1 << endl;
  73. return 0;
  74. }
Success #stdin #stdout 0.01s 5320KB
stdin
2 2
0 1
1 2
2 1
stdout
-1