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

const int MAXN = 100'005;

std::vector<std::vector<int>> v;

char beg[MAXN];
char tar[MAXN];

void YES() {
	printf("TAK\n");
}

void NO() {
	printf("NIE\n");
}

bool is_altering(int x, int o) {
	for (int a : v[x]) {
		if (a == o)
			continue;
		
		if (tar[a] == tar[x])
			return false;
		
		if (!is_altering(a, x))
			return false;
	}
	
	return true;
}

void solve() {
	v.clear();
	int n;
	scanf("%d", &n);
	
	v.resize(n+5);
	scanf("%s", beg);
	scanf("%s", tar);
	
	for (int i=0; i<n-1; i++) {
		int a, b;
		scanf("%d%d", &a, &b);
		a--;
		b--;
		v[a].push_back(b);
		v[b].push_back(a);
	}
	
	int cnt[2][2];
	cnt[0][0] = 0;
	cnt[0][1] = 0;
	cnt[1][0] = 0;
	cnt[1][1] = 0;
	
	bool eq = true;
	
	for (int i=0; i<n; i++) {
		cnt[0][beg[i]-'0']++;
		cnt[1][tar[i]-'0']++;
		
		if (beg[i] != tar[i])
			eq = false;
	}
	
	if (eq)
		return YES();
	
	if (cnt[0][0] == 0 && cnt[1][0] != 0)
		return NO();
	if (cnt[0][1] == 0 && cnt[1][1] != 0)
		return NO();
	
	if (is_altering(0, -1))
		return NO();
	
	for (int i=0; i<n; i++)
		if (v[i].size() > 2)
			return YES();
	
	if (n == 1)
		return YES();
	
// 	printf("No ealy cut\n");
	
	// We have a 2-colored path
	std::vector<int> p[2]; // init, target
	
	int a = 0;
	for (int i=0; i<n; i++) {
		if (v[i].size() == 1)
			a = i;
	}
	p[0].push_back(beg[a]-'0');
	p[1].push_back(tar[a]-'0');
	
	int b = v[a][0];
	
	while (2) {
		p[0].push_back(beg[b]-'0');
		p[1].push_back(tar[b]-'0');
		
		if (v[b].size() == 1)
			break;
		
		int tmp = b;
		b = v[b][0]+v[b][1]-a;
		a = tmp;
	}
	
// 	for (int i=0; i<2; i++) {
// 		for (int j=0; j<n; j++)
// 			printf("%d", p[i][j]);
// 		printf("\n");
// 	}
	
	int idx = 0;
	
	for (int i=0; i<n; i++) {
		while (p[1][i] != p[0][idx]) {
			idx++;
			if (idx >= n)
				return NO();
		}
	}
	
	return YES();
}

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