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
#include <bits/stdc++.h>
#include <vector>
using namespace std;
vector <int> v[100009] {};
int vis[100009] {};

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


string s,g;
int t,n,a,b,p,zm1=0,zm2=0,m,zn1,zn2;
bool x=0;
cin>>t;
for (int i=0;i<t;i++)
{
cin>>n>>s>>g;

for (int j=0;j<=n;j++)
{v[j].clear();
vis[j]=0;}

for (int j=0;j<n-1;j++)
{cin>>a>>b;
v[a].push_back(b);
v[b].push_back(a);}

zm1=0,zm2=0,x=0;

if (s==g) 
{cout<<"TAK\n";
continue;}

if (n==1) 
{cout<<"NIE\n";
continue;}

if (n==2)
{
if (s=="00" || s=="11")
{cout<<"NIE\n";
continue;}
else if (g=="00" || g=="11")
{cout<<"TAK\n";
continue;}
else {cout<<"NIE\n";
continue;}}

for (int j=1;j<n;j++)
{if (s[j]!=s[j-1]) 
{x=1;
break;}
}

if (x==0) 
{cout<<"NIE\n";
continue;}

x=0;

for (int j=1;j<=n;j++)
{
if (v[j].size()>=3)
{x=1;
break;}
}

if (x==1) 
{cout<<"TAK\n";
continue;}



for (int j=1;j<=n;j++)
{if (v[j].size()==1)
{p=j;
break;}
}

zn1=s[p-1];
zn2=g[p-1];
m=p;
vis[p]=1;
if (zn1!=zn2) {zm1=-1;}


for (int j=0;j<2;j++)
{if (vis[v[m][j]]==0)
{break;}
}

if (s[m-1]!=zn1) 
{zm1++;}

if (g[m-1]!=zn2)
{zm2++;}

for (int j=1;j<=n-1;j++)
{
for (int jj=0;jj<2;jj++)
{if (vis[v[m][jj]]==0)
{m=v[m][jj];
vis[m]=1;
break;}
}


if (s[m-1]!=zn1) 
{zm1++;
zn1=s[m-1];}

if (g[m-1]!=zn2)
{zm2++;
zn2=g[m-1];
}

}


if (zm1>=zm2) 
{cout<<"TAK\n";
continue;}
else {cout<<"NIE\n";
continue;}

}

return 0;
}