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

vector<int> g[100005];
vector<int> ord;
void get_ord(int v, int par) {
    ord.push_back(v);
    for (auto u : g[v]) {
        if (par != u)
            get_ord(u, v);
    }
}

int x;
int check_alternate(int v, int par, string &s) {
    int alt;
    if (s[v - 1] == '0') alt = 1;
    else alt = 2;
    for (auto u : g[v]) {
        if (u != par) {
            int alt_son = check_alternate(u, v, s);
            if (alt_son == 0) return 0;
            else if (alt_son == alt) return 0;
        }
    }

    return alt;
}

string solve() {
    int n, cnt[2] = {0, 0}, a, b;
    string src, dst;
    cin >> n >> src >> dst;
    for (int i = 1; i <= n; i++) {
        g[i].clear();
    }
    for (int i = 1; i < n; i++) {
        cin >> a >> b;
        g[a].push_back(b);
        g[b].push_back(a);
    }

    if (src == dst) return "TAK";
    int big = 0, idx = 1;
    for (int i = 1; i <= n; i++) {
        cnt[src[i-1] - '0']++;
        if (g[i].size() > 2) {
            big++;
            idx = i;
        }
    }
    int biale = cnt[0], czarne = cnt[1];

    if (cnt[0] == n || cnt[0] == 0) {
        return "NIE";
    }

    ord.clear();
    for (int i = 1; i <= n; i++) {
        if (g[i].size() == 1) {
            get_ord(i, 0);
            break;
        }
    }

    if (big == 0) {
        vector<int> blok_src, blok_dst;

        for (auto i : ord) {
            if (blok_src.empty() || blok_src.back() != src[i-1]) blok_src.push_back(src[i-1]);
            if (blok_dst.empty() || blok_dst.back() != dst[i-1]) blok_dst.push_back(dst[i-1]);
        }

       // cout << "jojo" << endl;
       // for (auto i : blok_src) cout << i << " ";cout << "\n";
       // for (auto i : blok_dst) cout << i << " " ;cout << "\n";
        if (blok_dst.size() > blok_src.size()) return "NIE";
        if (blok_dst.size() == blok_src.size()) return (blok_dst == blok_src ? "TAK" : "NIE");
        return "TAK";
    }
    
    int x = check_alternate(ord[0], 0, src);
    int y = check_alternate(ord[0], 0, dst);

    if (x == y || y == 0) return "TAK";

    return "NIE";
}

int32_t main() {
    ios_base::sync_with_stdio(0);
    int tests;
    cin >> tests;
    while (tests--) cout << solve() << "\n";
}