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

const int N = 1e5 + 5;

int t;
int n;
char S1[N], S2[N];
vector<int> kraw[N];
vector<int> order;
bitset<N> odw;

void dfs(int x) {
	odw[x] = true;
	order.push_back(x);
	for (int v : kraw[x]) {
		if (!odw[v]) {
			dfs(v);
		}
	}
	odw[x] = false;
}

void solve() {
	for (int i = 1; i <= n; i++) {
		if ((int)kraw[i].size() > 2 && S1[i - 1] == S2[i - 1]) {
			printf("TAK\n");
			return;
		}
	}
	printf("NIE\n");
}

int main() {
	scanf("%d", &t);
	while (t--) {
		scanf("%d", &n);
		scanf("%s", &S1);
		scanf("%s", &S2);
		for (int i = 1; i <= n; i++) {
			kraw[i].clear();
		}
		for (int i = 1; i < n; i++) {
			int a, b;
			scanf("%d%d", &a, &b);
			kraw[a].push_back(b);
			kraw[b].push_back(a);
		}
		bool f = false;
		for (int i = 0; i < n; i++) {
			f |= (S2[i] == '0');
		}
		for (int i = 0; i < n; i++) {
			f &= (S1[i] == '1');
		}
		if (f) {
			printf("NIE\n");
			continue;
		}
		for (int i = 0; i < n; i++) {
			f |= (S2[i] == '1');
		}
		for (int i = 0; i < n; i++) {
			f &= (S1[i] == '0');
		}
		if (f) {
			printf("NIE\n");
			continue;
		}

		for (int i = 1; i <= n; i++) {
			if ((int)kraw[i].size() > 2) {
				f = true;
				break;
			}
		}
		if (f) {
			solve();
			// printf("TAK\n");
			continue;
		}

		int ind = -1;
		for (int i = 1; i <= n; i++) {
			if ((int)kraw[i].size() == 1) {
				ind = i;
				break;
			}
		}
		order.clear();
		dfs(ind);

		int licz[2] = {0, 0};
		int last = -1;
		for (int v : order) {
			// cout << "kurcze " << last << endl;
			if (S1[v - 1] - '0' != last) {
				last = S1[v - 1] - '0';
				// cout << "siema " << last << " " << v << " " << S1[v - 1] << endl;
				// cout << S1 << endl;
				licz[last]++;
			}
		}
		last = -1;
		for (int v : order) {
			if (S2[v - 1] - '0' != last) {
				last = S2[v - 1] - '0';
				licz[last]--;
			}
		}
		if (licz[0] < 0 || licz[1] < 0 || (licz[0] == 0 && licz[1] == 0 && S1[order.front() - 1] != S2[order.front() - 1])) {
			printf("NIE\n");
		}
		else {
			printf("TAK\n");
		}

	}
}