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
#include <bits/stdc++.h>
using namespace std;
void print(const vector<bool>& v)
{
    for(int i=0; i<v.size(); ++i)
        cout << v[i];
    cout << endl;
}

void go()
{
    int n; cin >> n;
    string s; cin >> s;
    vector<bool> b_start(n);
    for(int i=0; i<n; ++i) b_start[i] = (s[i]=='1'?1:0);
    //print(b_start);
    cin >> s;
    vector<bool> b_stop(n);
    for(int i=0; i<n; ++i) b_stop[i] = (s[i]=='1'?1:0);
    //print(b_stop);

    vector<vector<int>> v(n);
    for(int i=0; i<n-1; ++i)
    {
        int x, y;
        cin >> x >> y;
        v[x-1].push_back(y-1);
        v[y-1].push_back(x-1);
        //cout << x << " - " << y << endl;
    }
//    for(int i=0; i<v.size(); ++i)
//    {
//        cout << i << ": ";
//        for(int j=0; j<v[i].size(); ++j)
//        {
//            cout << v[i][j] << " ";
//        }
//        cout << endl;
//    }

    if(b_start==b_stop) { cout << "TAK\n"; return; }

    set<vector<bool>> visited;
    visited.insert(b_start);

    queue<vector<bool>> frontier;
    frontier.push(b_start);

    while(!frontier.empty())
    {
        vector<bool> x = frontier.front();
        frontier.pop();
        for(int i=0; i<n; ++i)
            for(int j=0; j<v[i].size(); ++j)
                if(x[i]!=x[v[i][j]])
                {
                    x[i] = not x[i];
                    if(visited.count(x)==0)
                    {
                        if(x==b_stop) { cout << "TAK\n"; return; }
                        visited.insert(x);
                        frontier.push(x);
                    }
                    x[i] = not x[i];
                }
    }
    cout << "NIE\n";
}

int main()
{
    int t; cin >> t;
    while(t--) go();
    cout << flush;
}