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
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include <bits/stdc++.h>
using namespace std;
typedef long long lld;
typedef pair<int, int> pii;
typedef pair<lld, lld> pll;
#define ff first
#define ss second
#define mp make_pair
#define pb push_back

constexpr int N = 1 << 17;

int n;
vector<int> g[N];
char p[N];
char q[N];

void clear() {
	for (int i = 0; i <= n; ++i) {
		g[i].clear();
	}
}

int good_colors() {
	int cp = 0, cq = 0;
	bool same = true;
	
	for (int i = 1; i <= n; ++i) {
		p[i] -= '0';
		q[i] -= '0';
		cp |= int(p[i] + 1);
		cq |= int(q[i] + 1);
		
		same &= p[i] == q[i];
	}
	
	if (same) 
		return 2;
	
	if ((cp & cq) != cq) 
		return 0;
	
	if (cq != 3)
		return 2;
		
	return 1;
}

bool triple() {
	for (int i = 1; i <= n; ++i) {
		if (g[i].size() > 2)
			return true;
	}
	
	return false;
}

bool neighbours() {
	for (int v = 1; v <= n; ++v) {
		for (int x : g[v]) {
			if (q[v] == q[x])
				return true;
		}
	}
	
	return false;
}

int find_end() {
	for (int i = 1; i <= n; ++i) {
		if (g[i].size() == 1)
			return i;
	}
	
	return 0;
}

bool good_path() {
	int v = find_end();
	int x = g[v][0];
	int pc = 0, qc = 0;
	
	if (p[v] != q[v])
		++qc;
	
	while (true) {
		if (p[v] != p[x])
			++pc;
			
		if (q[v] != q[x])
			++qc;
		
		swap(v, x);
		
		if (g[v].size() <= 1)
			break;
		
		if (g[v][0] == x)
			x = g[v][1];
		else
			x = g[v][0];
	}
	
	return (qc <= pc);
}

void solve() {
	scanf("%d", &n);
	scanf("%s", p + 1);
	scanf("%s", q + 1);
	
	int a, b;
	for (int i = 1; i < n; ++i) {
		scanf("%d%d", &a, &b);
		g[a].pb(b);
		g[b].pb(a);
	}
	
	a = good_colors();
	if (a == 0) {
		puts("NIE");
		return;
	}
	if (a == 2){
		puts("TAK");
		return;
	}
	
	if (triple()) {
		if (neighbours()) {
			puts("TAK");
			return;
		}
		
		puts("NIE");
		return;
	}
	
	if (good_path()) {
		puts("TAK");
		return;
	}
	
	puts("NIE");
}

int main() {
	int T = 1;
	scanf("%d", &T);
	
	while (T--) {
		solve();
		clear();
	}
	
	return 0;
}