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

using namespace std;
string color[2];
int t, n;
vector <int> v[1000002];
bool check_path() {
    int root = 1;
    for (int i = 1; i <= n; i++) {
        if (v[i].size() <= 1) {
            root = i;
            break;
        }
    }
    int prev = root;
    int pos = root;
    char curr[2] = {color[0][root - 1], color[0][root - 1]};
    int counter = 0;
    while (1) {
        if (curr[0] != color[0][pos - 1])
            counter++;
        if (curr[1] != color[1][pos - 1])
            counter--;
        curr[0] = color[0][pos - 1];
        curr[1] = color[1][pos - 1];
        if (v[pos].size() == 0)
            break;
        if (v[pos][0] != prev) {
            int next = v[pos][0];
            prev = pos;
            pos = next;
        } else if (v[pos].size() > 1) {
            int next = v[pos][1];
            prev = pos;
            pos = next;
        } else {
            break;
        }
    }
    return counter >= 0;
}

int main() {
    cin >> t;
    while (t--) {
        for (int i = 1; i <= n; i++) {
            v[i].clear();
        }
        cin >> n;
        cin >> color[0] >> color[1];
        bool all_the_same = true;
        bool identical = true;
        for (int i = 0; i < n; i++) {
            if (color[0][i] != color[0][0])
                all_the_same = false;
            if (color[0][i] != color[1][i])
                identical = false;
        }
        bool is_path = true;
        bool two_same = false;
        for (int i = 1; i < n; i++) {
            int a, b;
            cin >> a >> b;
            v[a].push_back(b);
            v[b].push_back(a);
            if ((v[a].size() == 3) || (v[b].size() == 3))
                is_path = false;
            if (color[1][a-1] == color[1][b-1])
                two_same = true;
        }
        if (identical) {
            cout << "TAK" << endl;
            continue;
        }
        if (all_the_same || (!two_same)) {
            cout << "NIE" << endl;
            continue;
        }
        if (is_path && (!check_path())) {
            cout << "NIE" << endl;
            continue;
        }
        cout << "TAK" << endl;
    }
    return 0;
}