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
#pragma GCC optimize ("O3")
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef double K;
constexpr int INF = 0x3f3f3f3f;

#define FOR(i, b, e) for(int i = (b); i < (e); i++)
#define TRAV(x, a) for(auto &x: (a))
#define SZ(x) ((int)(x).size())
#define PB push_back
#define X first
#define Y second

constexpr int N = 1e5 + 5;

vi G[N];
int n;
string s1, s2;

bool bomble() {
	FOR(i, 0, n) TRAV(x, G[i]) if(s2[i] == s2[x]) return false;
	FOR(i, 0, n) if(s1[i] != s2[i]) return true;
	return false;
}

bool kolory() {
	bool c1 = count(s1.begin(), s1.end(), '0') > 0;
	bool c2 = count(s1.begin(), s1.end(), '1') > 0;
	bool d1 = count(s2.begin(), s2.end(), '0') > 0;
	bool d2 = count(s2.begin(), s2.end(), '1') > 0;
	return (!c1 && d1) || (!c2 && d2);
}

bool dfs(int v, int par, int bal) {
	if(s1[v] != s1[par]) bal++;
	if(s2[v] != s2[par]) bal--;
	TRAV(x, G[v]) if(x != par) return dfs(x, v, bal);
	return bal < 0;
}

bool sciezka() {
	FOR(i, 0, n) if(SZ(G[i]) > 2) return false;
	FOR(i, 0, n) if(SZ(G[i]) == 1) return dfs(i, i, -(s1[i] != s2[i]));
	return false;
}

void solve() {
	cin >> n >> s1 >> s2;
	FOR(i, 0, n) G[i].clear();
	FOR(i, 1, n) {
		int a, b;
		cin >> a >> b;
		a--, b--;
		G[a].PB(b);
		G[b].PB(a);
	}
	cout << (bomble() || kolory() || sciezka() ? "NIE\n" : "TAK\n");
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	int tt; cin >> tt;
	FOR(te, 0, tt) {
		// cout << "Case #" << te + 1 << ": ";
		solve();
	}
	// solve();
	return 0;
}