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
// Krzysztof Baranski (2021.12.12)
#include <cstdio>
#include <queue>
#include <unordered_set>
#include <iostream>
using namespace std;

unordered_set<string> visited;
string current_colors;
string target_colors;
vector<pair<int, int> > edges;

bool dfs(string& colors) {
    visited.insert(colors);

    if(colors == target_colors) return true;
    for(vector<pair<int, int> >::iterator it = edges.begin(); it != edges.end(); ++it) {
        int u = it->first;
        int v = it->second;
        bool result;

        if(colors[v] != colors[u]) {
            char c = colors[v];
            colors[v] = colors[u];
            if(!visited.count(colors)) {
                result = dfs(colors);
                if(result) return true;
            }

            colors[v] = c;
            c = colors[u];
            colors[u] = colors[v];

            if(!visited.count(colors)) {
                result = dfs(colors);
                if(result) return true;
            }

            colors[u] = c;
        }
    }

    return false;
}

int main() {
    int z;
    scanf("%d\n", &z);
    while(z--) {
        int n;
        scanf("%d\n", &n);
        
        cin >> current_colors;
        cin >> target_colors;

        visited.clear();
        edges.clear();

        int v, u;
        for(int i=0; i<n-1; ++i) {
            scanf("%d %d", &v, &u); v--; u--;
            edges.push_back(make_pair(v, u));
        }

        if(n==1 && current_colors[0]!=target_colors[0]) {
            printf("NIE\n");
            continue;
        }

        if(dfs(current_colors)) printf("TAK\n");
        else printf("NIE\n");
    }
    return 0;
}