#include <iostream> #include <vector> #include <algorithm> std::vector<bool> visited; std::vector<std::vector<int>> Adj; long long final_bitmask; int n; bool solve(long long bitmask) { if (bitmask == final_bitmask) return true; visited[bitmask] = true; for (int i = 0; i < n; i++) { for (int adjacent : Adj[i]) { bool adjacent_color = (bitmask >> adjacent) & 1; long long new_bitmask; if (adjacent_color) { new_bitmask = (bitmask | (1 << i)); } else { new_bitmask = (bitmask & (~(1 << i))); } if (!visited[new_bitmask]) { if (solve(new_bitmask)) return true; } } } return false; } int main() { int t; scanf("%d", &t); for (int i = 0; i < t; i++) { scanf("%d", &n); visited.clear(); visited.assign(1 << n, false); long long bitmask = 0; for (int i = 0; i < n; i++) { char state; scanf("%c", &state); while (state != '1' && state != '0') scanf("%c", &state); if (state == '1') { bitmask |= (1 << i); } } final_bitmask = 0; for (int i = 0; i < n; i++) { char state; scanf("%c", &state); while (state != '1' && state != '0') scanf("%c", &state); if (state == '1') { final_bitmask |= (1 << i); } } Adj.clear(); Adj.resize(n); for (int i = 0; i < n - 1; i++) { int a, b; scanf("%d %d", &a, &b); a--; b--; Adj[a].push_back(b); Adj[b].push_back(a); } if (solve(bitmask)) printf("TAK\n"); else printf("NIE\n"); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | #include <iostream> #include <vector> #include <algorithm> std::vector<bool> visited; std::vector<std::vector<int>> Adj; long long final_bitmask; int n; bool solve(long long bitmask) { if (bitmask == final_bitmask) return true; visited[bitmask] = true; for (int i = 0; i < n; i++) { for (int adjacent : Adj[i]) { bool adjacent_color = (bitmask >> adjacent) & 1; long long new_bitmask; if (adjacent_color) { new_bitmask = (bitmask | (1 << i)); } else { new_bitmask = (bitmask & (~(1 << i))); } if (!visited[new_bitmask]) { if (solve(new_bitmask)) return true; } } } return false; } int main() { int t; scanf("%d", &t); for (int i = 0; i < t; i++) { scanf("%d", &n); visited.clear(); visited.assign(1 << n, false); long long bitmask = 0; for (int i = 0; i < n; i++) { char state; scanf("%c", &state); while (state != '1' && state != '0') scanf("%c", &state); if (state == '1') { bitmask |= (1 << i); } } final_bitmask = 0; for (int i = 0; i < n; i++) { char state; scanf("%c", &state); while (state != '1' && state != '0') scanf("%c", &state); if (state == '1') { final_bitmask |= (1 << i); } } Adj.clear(); Adj.resize(n); for (int i = 0; i < n - 1; i++) { int a, b; scanf("%d %d", &a, &b); a--; b--; Adj[a].push_back(b); Adj[b].push_back(a); } if (solve(bitmask)) printf("TAK\n"); else printf("NIE\n"); } } |