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
#include <cstdio>
#include <cstring>
#include <vector>

constexpr int N = 100 * 1000 + 2;
char orig[N], wanted[N];

void process_line(int n, const std::vector<std::vector<int>>& neighbours) {
    int v1 = 0, v2 = 0;
    for (int i = 1; i <= n; ++i) {
        if (neighbours[i].size() == 1) {
            v1 = i;
            v2 = neighbours[v1][0];
            break;
        }
    }

    bool same_start = orig[v1] == wanted[v1];
    int orig_changes = 0, wanted_changes = 0;

    while (neighbours[v2].size() > 1) {
        if (orig[v1] != orig[v2]) {
            orig_changes++;
        }
        if (wanted[v1] != wanted[v2])
        {
            wanted_changes++;
        }
        int v3 = neighbours[v2][0] == v1 ? neighbours[v2][1] : neighbours[v2][0];
        v1 = v2;
        v2 = v3;
    }

    if (orig[v1] != orig[v2]) {
        orig_changes++;
    }
    if (wanted[v1] != wanted[v2])
    {
        wanted_changes++;
    }

    if (orig_changes > wanted_changes || (orig_changes == wanted_changes && same_start)) {
        printf("TAK\n");
    } else {
        printf("NIE\n");
    }
}

int main() {
    int t;
    scanf("%d", &t);
    while (t--) {
        int n;
        scanf("%d", &n);
        scanf(" %s %s\n", orig + 1, wanted + 1);
        std::vector<std::vector<int>> neighbours;
        neighbours.resize(n + 1);
        int a, b;
        bool good_edge = false;
        for (int i = 1; i < n; ++i) {
            scanf("%d%d", &a, &b);
            neighbours[a].push_back(b);
            neighbours[b].push_back(a);
            if (wanted[a] == wanted[b]) {
                good_edge = true;
            }
        }
        if (strcmp(orig + 1, wanted + 1) == 0) {
            printf("TAK\n");
            continue;
        }
        bool z = false, o = false;
        for (int i = 1; i <= n; ++i) {
            if (orig[i] == '0') {
                z = true;
            } else {
                o = true;
            }
        }
        if ((!z) || (!o)) {
            printf("NIE\n");
            continue;
        }

        size_t deg = 0;
        for (int i = 1; i <= n; ++i) {
            deg = std::max(deg, neighbours[i].size());
        }
        if (deg < 3) {
            process_line(n, neighbours);
            continue;
        }

        if (good_edge) {
            printf("TAK\n");
        } else {
            printf("NIE\n");
        }
    }
    return 0;
}