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

using namespace std;
typedef long long LL;

const int MAX = 1e5+5;
vector<int> tree[MAX];
string str1, str2;

bool check(int root) {
    unordered_set<int> s;
    deque<int> q;
    q.push_back(root);
    s.insert(root);

    bool allOnes1 = true;
    bool allZeros1 = true;
    bool allOnes2 = true;
    bool allZeros2 = true;
    size_t maxDegree = 0;
    bool hasEdge = false;
    int deg1 = 0;

    while(!q.empty()) {
        int top = q.front();
        q.pop_front();

        if(str1[top-1] == '0') allOnes1 = false;
        else allZeros1 = false;
        if(str2[top-1] == '0') allOnes2 = false;
        else allZeros2 = false;

        if(maxDegree < tree[top].size()) {
            maxDegree = tree[top].size();
        }
        if(tree[top].size() == 1)
            deg1 = top;

        for(int i = 0; i < tree[top].size(); ++i) {
            int v = tree[top][i];
            if(str2[v-1] == str2[top-1]) hasEdge = true;
            if(s.count(v)) continue;
            q.push_back(v);
            s.insert(v);
        }
    }

    if(allOnes1 && allOnes2) return true;
    if(allOnes1 && !allOnes2) return false;
    if(allZeros1 && allZeros2) return true;
    if(allZeros1 && !allZeros2) return false;

    if(maxDegree < 3) {
        int v = deg1;
        int prev = 0;
        vector<int> g1, g2;
        while(1) {
            g1.push_back(str1[v-1]);
            g2.push_back(str2[v-1]);
            if(v != deg1 && tree[v].size() == 1) break;
            int next = tree[v].size() == 1 ? tree[v][0] : (tree[v][0] == prev ? tree[v][1] : tree[v][0]);
            prev = v;
            v = next;
        }
        vector<int> gg1, gg2;
        for(int i = 0; i < g1.size(); ++i) {
            if(i == 0 || g1[i] != g1[i-1]) gg1.push_back(g1[i]);
            if(i == 0 || g2[i] != g2[i-1]) gg2.push_back(g2[i]);
        }
        if(gg1.size() > gg2.size()) return true;
        if(gg1.size() < gg2.size()) return false;
        return gg1[0] == gg2[0];
    } else {
        if(hasEdge) return true;
    }
    return false;
}

void solve() {
    int n, a, b;
    cin >> n;
    cin >> str1 >> str2;

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

    if(str1 == str2 || check(1)) {
        cout << "TAK\n";
    } else {
        cout << "NIE\n";
    }
}

int main() {
    ios_base::sync_with_stdio(false);
   int t;
   cin >> t;
   while(t--) solve();
}