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
#include <vector>
#include <iostream>
using namespace std;

void get_path_stats(const vector<vector<int>> &G, const string &colors, int v, int prev, int &seqs) {
    // cerr << "v = " << v << endl;
    if (prev == -1)
        seqs = 1;
    else if(colors[prev] != colors[v])
        seqs++;

    for (int nei : G[v])
        if (nei != prev)
            get_path_stats(G, colors, nei, v, seqs);
}

bool solve(const string &before, const string &after, const vector<vector<int>> &G, int n) {
    // cerr << "N = " << n << endl;
    if(before == after)
        return true;

    //calculate stats
    int leaves = 0, example_leaf = -1, b0 = 0, b1 = 0, a0 = 0, a1 = 0;
    for (int i = 0; i < n; i++) {
        if (G[i].size() == 1) {
            leaves++;
            example_leaf = i;
        }
        if (before[i] == '0')
            b0++;
        else
            b1++;
        if (after[i] == '0')
            a0++;
        else
            a1++;
    }

    //test colorsets
    if (a0 && !b0 || a1 && !b1)
        return false;

    //if trivial
    if (n == 1)
        return true;

    //non-trivial case A = path
    if (leaves < 3) {
        int bl = 0, al = 0;
        get_path_stats(G, before, example_leaf, -1, bl);
        get_path_stats(G, after, example_leaf, -1, al);

        if (before[example_leaf] == after[example_leaf])
            return bl >= al;
        else
            return bl - 1 >= al;
    }

    //non-trivial case B = not path
    else {
        for(int i = 0; i < n; i++)
            for(int nei : G[i])
                if(after[nei] == after[i])
                    return true;
        return false;
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;

        string before, after;
        cin >> before >> after;

        vector<vector<int>>G(n + 1);
        for (int i = 1; i < n; i++){
            int x, y;
            cin >> x >> y;
            G[x - 1].push_back(y - 1);
            G[y - 1].push_back(x - 1);
        }

        if (solve(before, after, G, n))
            cout << "TAK\n";
        else
            cout << "NIE\n";
    }

    return 0;
}