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
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include <unordered_set>

namespace {
  using std::cin;
  using std::cout;
  using std::string;
  using std::endl;

  using test_size_t = size_t;
  using tree_size_t = size_t;
  using tree_data_t = string;
  using edge_t = std::pair<tree_size_t, tree_size_t>;
  using tree_edges_t = std::vector<edge_t>;
  using tree_cases_t = std::vector<tree_data_t>;
  using tree_cases_comp_t = std::unordered_set<tree_data_t>;

  string const ANS_T = "TAK";
  string const ANS_N = "NIE";
}

int main() {
  test_size_t t;
  tree_size_t n;
  tree_data_t curr_tree;
  char node;
  tree_data_t fin_tree;
  tree_cases_t tree_cases;
  tree_cases_comp_t tree_cases_comp;
  edge_t edge;
  tree_edges_t tree_edges;
  bool found = false;
  size_t curr_tree_id = 0;   

  cin >> t;
  for (test_size_t k_t = 0; k_t < t; ++k_t) {
    cin >> n;
    cin >> curr_tree;
    tree_cases.push_back(curr_tree);
    tree_cases_comp.insert(curr_tree);
    cin >> fin_tree;    
    for (tree_size_t k_n = 0; k_n < n - 1; ++k_n) {
      cin >> edge.first;
      cin >> edge.second;      
      --edge.first;
      --edge.second;
      tree_edges.push_back(edge);
    }
    curr_tree_id = 0;
    found = false;
    while (!found && curr_tree_id < tree_cases.size()) {
      if (fin_tree.compare(tree_cases[curr_tree_id]) == 0) {
        found = true;
      } else {
        for (auto const & e: tree_edges) {
          curr_tree = tree_cases[curr_tree_id];
          if (curr_tree[e.first] != curr_tree[e.second]) {
            node = curr_tree[e.first];
            curr_tree[e.first] = curr_tree[e.second];
            if (tree_cases_comp.insert(curr_tree).second)
              tree_cases.push_back(curr_tree);
            curr_tree[e.first] = node;
            curr_tree[e.second] = node;
            if (tree_cases_comp.insert(curr_tree).second)
              tree_cases.push_back(curr_tree);
          }
        }
        ++curr_tree_id;
      }
    }
    if (found)
      cout << ANS_T << endl;
    else
      cout << ANS_N << endl;
    tree_cases.clear();
    tree_cases_comp.clear();
    tree_edges.clear();
  }
  return 0;
}