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
#include <bits/stdc++.h>
#define QED return 0;}
#define main() int main(){
using namespace std;

int t, n, a, b, p, cnt;
string s1, s2, s3, s4;
bool is0, is1, is02, is12;
bool che, xd;
int in[100007];
bool odw[100007];
int order[100007];
int orderrev[100007];
vector <int> g[100007];

void dfs(int v){
	odw[v] = 1;
	order[v] = ++cnt;
	orderrev[cnt] = v;
	for(int i = 0; i < g[v].size(); i++){
		if(odw[g[v][i]]) continue;
		dfs(g[v][i]);
	}
}

main()
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);

	cin >> t;
	while(t--){
	
		che = 0;
		is0 = 0;
		is1 = 0;
		is02 = 0;
		is12 = 0;
		cnt = 0;
		p = 1;
		s3.clear();
		s4.clear();
		for(int i = 1; i <= n; i++){
			in[i] = 0;
			odw[i] = 0;
			order[i] = 0;
			orderrev[i] = 0;
			g[i].clear();
		}
	
		cin >> n >> s1 >> s2;
		s3 = s1;
		for(int i = 1; i < n; i++){
			cin >> a >> b;
			g[a].push_back(b);
			g[b].push_back(a);
			in[a]++;
			in[b]++;
			if(in[a] == 3 || in[b] == 3) che = 1;
		}
		
		for(int i = 0; i < n; i++){
			if(s1[i] == '0') is0 = 1;
			else is1 = 1;
		}
		for(int i = 0; i < n; i++){
			if(s2[i] == '0') is02 = 1;
			else is12 = 1;
		}
		
		if(s1 == s2){
			cout << "TAK" << '\n';
			continue;
		}
		if(!is0 && is02 || !is1 && is12){
			cout << "NIE" << '\n';
			continue;
		}
		
		if(che == 1){
			xd = 0;
			for(int i = 1; i <= n; i++){
				for(int j = 0; j < g[i].size(); j++){
					if(s2[i - 1] == s2[g[i][j] - 1]) xd = 1;
					if(xd) break;
				}
				if(xd) break;
			}
			if(xd) cout << "TAK" << '\n';
			else cout << "NIE" << '\n';
			continue;
		}
		
		for(int i = 1; i <= n; i++){
			if(in[i] == 1){
				p = i;
				break;
			}	
		}
		dfs(p);
		s3 = s1[orderrev[1] - 1];
		s4 = s2[orderrev[1] - 1];
		for(int i = 2; i <= n; i++){
			if(s1[orderrev[i] - 1] != s3[s3.size() - 1]) s3 += s1[orderrev[i] - 1];
			if(s2[orderrev[i] - 1] != s4[s4.size() - 1]) s4 += s2[orderrev[i] - 1];
		}
		//cout << s3 << ' ' << s4 << ' ';
		if(s3.size() > s4.size() || s3 == s4) cout << "TAK" << '\n';
		else cout << "NIE" << '\n';
	}

QED