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

bool same_colours(string &a, string &b) {
	for (uint i = 0; i < a.size(); i++) 
		if (a[i] != b[i]) return false;
	
	return true;
}

bool no_double(string &cols, vector<vector<int>> &e) {
	for (uint i = 1; i <= cols.size(); i++)
		for (int other : e[i]) 
			if (cols[i-1] == cols[other-1]) return false;
			
	return true;
}

bool has_triple(vector<vector<int>> &e) {
	for (uint i = 1; i < e.size(); i++)
		if (e[i].size() > 2) return true;

	return false;
}

int count_stripes(string &cols, vector<vector<int>> &e) {
	int result = 0;
	
	for (uint i = 1; i <= cols.size(); i++)
		for (int other : e[i]) 
			if (cols[i-1] != cols[other-1]) result++;
			
	return result / 2;
}

bool same_leaf_colour(string &a, string &b, vector<vector<int>> &e) {
	for (uint i = 1; i <= a.size(); i++) {
		if (e[i].size() != 1) continue;
		
		if (a[i-1] != b[i-1]) return false;
	}
	
	return true;
}

bool has_both_colours(string &a) {
	bool is_there[2];
	for (char c : a)
		is_there[c - '0'] = true;
		
	return is_there[0] && is_there[1];
}

bool solve() {
	int n; cin >> n;
	
	string col_old, col_new;
	cin >> col_old >> col_new;
	
	vector<vector<int>> e(n+1);
	for (int i = 0; i < n-1; i++) {
		int a, b; cin >> a >> b;
		e[a].push_back(b);
		e[b].push_back(a);
	}
	
	if (same_colours(col_old, col_new)) return true;
	if (no_double(col_new, e)) return false;
	if (!has_both_colours(col_old)) return false;
	if (has_triple(e)) return true;
	
	int strp_old = count_stripes(col_old, e);
	int strp_new = count_stripes(col_new, e);
	
	if (strp_old < strp_new) return false;
	if (strp_new < strp_old) return true;
	
	return same_leaf_colour(col_old, col_new, e);
}

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0);
	
	int t; cin >> t; while(t--) 
		cout << (solve() ? "TAK" : "NIE") << endl;
	
	return 0;
}