#pragma GCC optimize ("Ofast,inline,unroll-loops") #include <cstdio> #include <vector> const int N = 25; int t, n; std::vector<int> adj[N + 10]; char a[N + 10], b[N + 10]; int s_mask, t_mask, que[1 << N], can[1 << N], tim, cnt; int main() { scanf("%d", &t); while(t--) { scanf("%d", &n); scanf("%s", a); scanf("%s", b); s_mask = 0, t_mask = 0; for(int i = 0; i < n; i++) s_mask = (s_mask << 1) + a[i] - '0'; for(int i = 0; i < n; i++) t_mask = (t_mask << 1) + b[i] - '0'; for(int i = 0; i < n - 1; i++) { int u, v; scanf("%d%d", &u, &v); u--, v--; adj[u].push_back(v); adj[v].push_back(u); } cnt = 0; tim++; can[s_mask] = tim; que[cnt++] = s_mask; for(int i = 0; i < cnt && can[t_mask] != tim; i++) { int u = que[i]; for(int j = 0; j < n; j++) { for(int v : adj[j]) if((u >> j & 1) != (u >> v & 1)) { if(que[i] >> j & 1) v = u | (1 << v); else v = u & ~(1 << v); if(can[v] != tim) { can[v] = tim; que[cnt++] = v; } } } } if(can[t_mask] == tim) puts("TAK"); else puts("NIE"); for(int i = 0; i < n; i++) adj[i].clear(); } }
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 | #pragma GCC optimize ("Ofast,inline,unroll-loops") #include <cstdio> #include <vector> const int N = 25; int t, n; std::vector<int> adj[N + 10]; char a[N + 10], b[N + 10]; int s_mask, t_mask, que[1 << N], can[1 << N], tim, cnt; int main() { scanf("%d", &t); while(t--) { scanf("%d", &n); scanf("%s", a); scanf("%s", b); s_mask = 0, t_mask = 0; for(int i = 0; i < n; i++) s_mask = (s_mask << 1) + a[i] - '0'; for(int i = 0; i < n; i++) t_mask = (t_mask << 1) + b[i] - '0'; for(int i = 0; i < n - 1; i++) { int u, v; scanf("%d%d", &u, &v); u--, v--; adj[u].push_back(v); adj[v].push_back(u); } cnt = 0; tim++; can[s_mask] = tim; que[cnt++] = s_mask; for(int i = 0; i < cnt && can[t_mask] != tim; i++) { int u = que[i]; for(int j = 0; j < n; j++) { for(int v : adj[j]) if((u >> j & 1) != (u >> v & 1)) { if(que[i] >> j & 1) v = u | (1 << v); else v = u & ~(1 << v); if(can[v] != tim) { can[v] = tim; que[cnt++] = v; } } } } if(can[t_mask] == tim) puts("TAK"); else puts("NIE"); for(int i = 0; i < n; i++) adj[i].clear(); } } |