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
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <string>
#include <bitset>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <sstream>
#include <stack>
#include <iomanip>
#include <assert.h>
using namespace std;
#define pb push_back
#define mp make_pair
typedef pair<int,int> pii;
typedef long long ll;
typedef double ld;
typedef vector<int> vi;
#define fi first
#define se second
#define fe first
#define FO(x) {freopen(#x".in","r",stdin);freopen(#x".out","w",stdout);}
#define Edg int M=0,fst[SZ],vb[SZ],nxt[SZ];void ad_de(int a,int b){++M;nxt[M]=fst[a];fst[a]=M;vb[M]=b;}void adde(int a,int b){ad_de(a,b);ad_de(b,a);}
#define Edgc int M=0,fst[SZ],vb[SZ],nxt[SZ],vc[SZ];void ad_de(int a,int b,int c){++M;nxt[M]=fst[a];fst[a]=M;vb[M]=b;vc[M]=c;}void adde(int a,int b,int c){ad_de(a,b,c);ad_de(b,a,c);}
#define es(x,e) (int e=fst[x];e;e=nxt[e])
#define esb(x,e,b) (int e=fst[x],b=vb[e];e;e=nxt[e],b=vb[e])
#define SZ 1234567
int T,n,deg[SZ]; Edg
char c0[SZ],c1[SZ];
int sn=0,ss[SZ];
void dfs(int x,int f=0) {
	ss[++sn]=x;
	for esb(x,e,b) if(b!=f) dfs(b,x);
}
void sol() {
	scanf("%d",&n); M=0;
	for(int i=1;i<=n;++i) fst[i]=deg[i]=0;
	scanf("%s%s",c0+1,c1+1);
	for(int i=1,a,b;i<n;++i)
		scanf("%d%d",&a,&b),adde(a,b),++deg[a],++deg[b];
	int both=0,bb=0;
	for(int i=1;i<=n;++i)
		both|=1<<(c0[i]-'0'),bb|=1<<(c1[i]-'0');
	bool nc=0;
	for(int i=1;i<=n;++i) if(deg[i]>2) nc=1;
	int d1=0,sb=0;
	for(int i=1;i<=n;++i) {
		if(deg[i]!=1) sb=i;
	}
	for(int i=1;i<=n;++i) d1+=(deg[i]==1);
	bool eq=1;
	for(int i=1;i<=n;++i) eq&=c0[i]==c1[i];
	if(eq) {
		puts("TAK");
		return;
	}
	if((both&bb)!=bb) {
		puts("NIE");
		return;
	}
	bool jg=1;
	for(int i=1;i<=n;++i)
		for esb(i,e,b) if(c1[i]==c1[b]) jg=0;
	if(jg) {
		puts("NIE");
		return;
	}
	if(nc||n==1) {
		puts("TAK");
		return;
	}
	int x=1;
	while(deg[x]!=1) ++x;
	sn=0; dfs(x);
	int j=1;
	for(int i=1;i<=n;++i) {
		int l=i;
		while(i+1<=n&&c1[ss[i+1]]==c1[ss[i]]) ++i;
		while(j<=n&&c0[ss[j]]!=c1[ss[i]]) ++j;
		if(j>n) {
			puts("NIE");
			return;
		}
	}
	puts("TAK");
}
int main()
{
	scanf("%d",&T);
	while(T--) sol();
}