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
#include <bits/stdc++.h>
using namespace std;

const int N = 1e6 + 5;

#define st first
#define nd second

typedef pair<int,int> pun;
typedef long long ll;

vector<vector<int>> v;
string s1, s2;
ll s1_int, s2_int;

set<ll> mem;
queue<ll> que;

bool backtrack(int s) {
	que.push(s);
	mem.insert(s);
	if (s == s2_int) return true;
	while (!que.empty()) {
		ll s = que.front();
		que.pop();
		for (int x = 1; x < v.size(); x ++) {
			for (int y : v[x]) {
				if (((s & (1LL<<(x-1))) != 0) == ((s & (1LL<<(y-1))) != 0)) continue;
				ll v = s;
				v ^= (1LL<<(x-1));
				if (mem.find(v) == mem.end()) {
					que.push(v);
					mem.insert(v);
					if (v == s2_int) return true;
				}
				ll w = s;
				w ^= (1LL<<(y-1));
				if (mem.find(w) == mem.end()) {
					que.push(w);
					mem.insert(w);
					if (w == s2_int) return true;
				}
			}
		}
	}
	return false;
}

bool test() {
	int n;
	cin >> n;
	cin >> s1 >> s2;
	v.clear();
	v.resize(n+1);
	for (int i = 0; i < n - 1; i ++ ) {
		int a, b;
		cin >> a >> b;
		v[a].push_back(b);
		v[b].push_back(a);
	}
	mem.clear();
	que = queue<ll>();
	s1_int = 0;
	s2_int = 0;
	for (int i = 0; i < n; i ++) {
		if (s1[i] == '1') s1_int += (1LL<<i);
		if (s2[i] == '1') s2_int += (1LL<<i);
	}
	return backtrack(s1_int);
}

int main() {
	int t;
	cin >> t;
	while (t--) {
		cout << (test() ? "TAK" : "NIE") << "\n";
	}
}