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;

const int N = 100'007;
const int INF = 1'000'000'007;

int n;
vector <int> G[N];

char src[N];
char goal[N];

bool check(vector <int> line)
{
    int diffs_src = 0, diffs_goal = 0;
    for (int i = 1; i < n; ++i) {
        int v = line[i], prv = line[i - 1];
        diffs_src += src[v] != src[prv];
        diffs_goal += goal[v] != goal[prv];
    }

    if (src[line[0]] != goal[line[0]]) {
        diffs_src--;
    }

    return diffs_src >= diffs_goal;
}

int main()
{
    int cases;
    scanf("%d", &cases);

    while(cases--) {
        scanf("%d", &n);
        scanf("%s", src + 1);
        scanf("%s", goal + 1);

        for (int i = 1; i <= n; ++i) {
            G[i].clear();
        }

        bool is_bipartite = true;
        for (int i = 1; i < n; ++i) {
            int u, v;
            scanf("%d %d", &u, &v);

            is_bipartite &= goal[u] != goal[v];

            G[u].push_back(v);
            G[v].push_back(u);
        }

        int max_deg = 0;
        bool is_unicolor = true;
        bool are_equal = true;

        for (int i = 1; i <= n; ++i) {
            max_deg = max(max_deg, (int)G[i].size());
            are_equal &= src[i] == goal[i];
            is_unicolor &= src[i] == src[1];
        }

        if (are_equal) {
            puts("TAK");
            continue;
        }

        if (is_unicolor) {
            puts("NIE");
            continue;
        }

        if (max_deg > 2) {
            puts(is_bipartite ? "NIE" : "TAK");
            continue;
        }

        int root = 1, prv = -1;
        for (int i = 1; i <= n; ++i) {
            if (G[i].size() == 1) {
                root = i;
                break;
            }
        }

        vector <int> line = {root};
        while ((int)line.size() < n) {
            for (auto v: G[root]) {
                if (v != prv) {
                    prv = root;
                    root = v;
                    break;
                }
            }

            line.push_back(root);
        }

        puts(check(line) ? "TAK" : "NIE");
    }
}