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
// Autor: Mikołaj Janusz
#include <bits/stdc++.h>

typedef long long ll;

using namespace std;

bool bfs(ll x, vector<vector<ll>>& graph, vector<bool>& colors, vector<bool>& targets, set<ll>& visited) {
    if (colors[x] == targets[x]) {
        return true;
    }

    queue<ll> q;
    q.push(x);
    visited.insert(x);

    while (!q.empty()) {
        ll cur = q.front();
        q.pop();      

        for (ll i = 0; i != graph[cur].size(); i++) {
            if (graph[cur][i] && (visited.find(i) == visited.end())) {
                if (colors[i] == targets[x]) {
                    if (bfs(i, graph, colors, targets, visited)) {
                        return true;
                    }
                }

                q.push(i);
                visited.insert(i);
            }
        }
    }

    return false;
}

int main() {
    ios::sync_with_stdio(false);
    ll tests;
    cin >> tests;

    for (ll t = 0; t < tests; t++) {
        ll n;
        cin >> n;

        string s_col;
        string s_tar;
        string result = "TAK";
        vector<vector<ll>> graph(n + 3);
        vector<bool> colors(n+1);
        vector<bool> targets(n+1);

        cin >> s_col >> s_tar;
        for (ll i = 1; i <= n; i++) {
            colors[i] = (s_col[i-1] == '1');
            targets[i] = (s_tar[i-1] == '1');
        }

        for (ll i = 0; i < n - 1; i++) {
            ll x, y;
            cin >> x >> y;
            graph[x].push_back(y);
            graph[y].push_back(x);
        }

        for (ll i = 1; i <= n; i++) {
            if (colors[i] != targets[i]) {
                set<ll> visited;
                if (!bfs(i, graph, colors, targets, visited)) {
                    result = "NIE";
                    break;
                }
            }
        }
        
        cout << result << endl;
    }


    return 0;
}