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
#include<bits/stdc++.h>
using namespace std;

int32_t main(){
    ios::sync_with_stdio(false);
    int TC;
    cin >> TC;
    for(int TCC=1;TCC<=TC;TCC++) {
        int n;
        cin >> n;

        string col2(n,' '), col22(n,' ');
        vector<vector<int> > graf(n);

        string A,B;
        cin >> A >> B;
        for(int i=1;i<n;i++){
            int a,b;
            cin >> a >> b;
            graf[a-1].push_back(b-1);
            graf[b-1].push_back(a-1);
        }

        if(count(A.begin(),A.end(),'0') == 0 && count(B.begin(), B.end(), '0') > 0) {cout<<"NIE\n"; continue;}
        if(count(A.begin(),A.end(),'1') == 0 && count(B.begin(), B.end(), '1') > 0) {cout<<"NIE\n"; continue;}

        function<void(int,int,int)> dfs = [&](int cur, int p, int x) {
            col2[cur] =  "01"[x];
            col22[cur] = "01"[x^1];
            for(auto a:graf[cur]) {
                if(a != p)
                    dfs(a,cur,x^1);
            }
        };

        bool tree = 0;
        for(auto a:graf)
            if(a.size() >= 3)
                tree = 1;
        if(tree) {
            dfs(0,0,0);
            if(A == B)
                cout<<"TAK\n";
            else if(B == col2 || B == col22)
                cout<<"NIE\n";
            else
                cout<<"TAK\n";
        }
        else {
            int r = 0;
            while(graf[r].size() == 2) r++;
            
            char pa = '2', pb = '2';
            int s = r, prv = -1;
            int cntA=0,cntB=0;
            for(int i=0;i<n;i++) {
                if(A[s] != pa)
                    cntA++;
                if(B[s] != pb)
                    cntB++;
                pa = A[s];
                pb = B[s];
                if(i+1 == n) break;
                for(auto a:graf[s]) {
                    if(a != prv) {
                        prv = s;
                        s = a;
                        break;
                    }
                }
            }
            if(A[r] != B[r]) cntA--;
            if(A[s] != B[s]) cntA--;
            if(cntA >= cntB)
                cout<<"TAK\n";
            else cout<<"NIE\n";
        }
    }
}