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
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <deque>
using namespace std;

int T;
string solve(int t);

int main()
{
    cin >> T;
    for(int i=0; i<T; i++) cout << solve(i) << endl;
    return 0;
}

string solve(int t) {
    
    int N;
    map<int, set<int>> spot;
    string B, E;
    set<string> visited;
    deque<string> q;
    
    cin >> N >> B >> E;
    
    for(int i=1; i<N; i++) {
        int a, b;
        cin >> a >> b;
        spot[a-1].insert(b-1);
        spot[b-1].insert(a-1);
    }
    
    q.push_back(B);
    visited.insert(B);
    
    while(!q.empty()) {
        string curNode = q.front(); q.pop_front();
        if(curNode == E) return "TAK";
        for(int u=0; u<N; u++) for(int v : spot[u]) {
            string nextNode = curNode;
            nextNode[v] = curNode[u];
            if(visited.count(nextNode)) continue;
            q.push_back(nextNode);
            visited.insert(nextNode);
        }
    }
    return "NIE";
}