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
//Ada Kołodziejczak
//Zadanie Drzewo czerwono-czarne
#include<bits/stdc++.h>
#define pb push_back
using namespace std;
int n, q, a, b, l1, l0;
bool t[2][100005];
string s, ss;
vector<int> v[100005];
bool st3, dwa, p0, k0, p1, k1, bl1, re1, bl0, re0;

void dfs(int w, int o)
{
    k0=t[0][w];
    k1=t[1][w];

    if(v[w].size()>2) st3=1;
    
    if(t[1][w]!=t[1][o]&&o!=0) ++l1;
    else if(o!=0) dwa=1;
    
    if(t[0][w]!=t[0][o]&&o!=0) ++l0;
    
    if(t[0][w]) bl0=1;
    if(t[1][w]) bl1=1;
    if(!t[0][w]) re0=1;
    if(!t[1][w]) re1=1;

    for(auto i: v[w])
    {
        if(i==o) continue;
        else dfs(i, w);
    }
    
    p0=t[0][w];
    p1=t[1][w];
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin>>q;
for(int z=0; z<q; ++z)    
{
    cin>>n>>s;
    for(int i=0; i<n; ++i)
    {
        t[0][i+1]=s[i]-'0';
    }
    cin>>ss;
    for(int i=0; i<n; ++i)
    {
        t[1][i+1]=ss[i]-'0';
    }
 
    for(int i=1; i<n; ++i)
    {
        cin>>a>>b;
        v[a].pb(b);
        v[b].pb(a);
    }

    for(int i=1; i<=n; ++i)
    {
        if(v[i].size()==1)
        {
            dfs(i, 0);
            break;
        }
    }   
    if(!bl0&&!re0)dfs(1, 0);

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

    else if(st3)
    {
        if(dwa)
        {
            if(bl1&&!bl0||re1&&!re0) cout<<"NIE\n";
            else cout<<"TAK\n";
        } 
        else cout<<"NIE\n";
    }

    else
    {
        if(l0<l1) cout<<"NIE\n";
        else
        {
            if(bl0&&!re0)
            {
                if(re1) cout<<"NIE\n";
                else cout<<"TAK\n";
            }
            else if(!bl0&&re0)
            {
                if(bl1) cout<<"NIE\n";
                else cout<<"TAK\n";
            }
            else if(p1==p0&&k1==k0) cout<<"TAK\n";
            else if((p1!=p0&&k1==k0)||(p1==p0&&k1!=k0))
            {
                if(l0-1<l1) cout<<"NIE\n";
                else cout<<"TAK\n";
            }
            else
            {
                if(l0-2<l1) cout<<"NIE\n";
                else cout<<"TAK\n";
            }
        }
    }

    for(int i=1; i<=n; ++i)
    {
        v[i].resize(0);
    }

    st3=0;
    dwa=0;
    l1=0;
    l0=0;
    bl1=0;
    bl0=0;
    re0=0;
    re1=0;
}
}