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
84
85
86
87
88
89
90
91
92
93
94
#include <bits/stdc++.h>

using namespace std;

struct Tree
{
  struct Node
  {
    vector<size_t> neighbors;
  };
  size_t size;
  vector<Node> nodes;
};

struct TestCase
{
  Tree tree;
  vector<bool> initial_coloring;
  vector<bool> desired_coloring;
};

TestCase read_test_case();
void solve_test_case(TestCase);

int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  size_t test_case_count;
  cin >> test_case_count;
  while (test_case_count--) solve_test_case(read_test_case());
}

TestCase read_test_case()
{
  TestCase tc;
  cin >> tc.tree.size;
  tc.initial_coloring.resize(tc.tree.size);
  tc.desired_coloring.resize(tc.tree.size);
  tc.tree.nodes.resize(tc.tree.size);

  string initial;
  cin >> initial;
  for (size_t i = 0; i < tc.tree.size; i++)
    tc.initial_coloring[i] = initial[i] == '1';
  string desired;
  cin >> desired;
  for (size_t i = 0; i < tc.tree.size; i++)
    tc.desired_coloring[i] = desired[i] == '1';
  for (size_t _ = 0; _ < tc.tree.size - 1; _++)
  {
    size_t a, b;
    cin >> a >> b;
    a--;
    b--;
    tc.tree.nodes[a].neighbors.push_back(b);
    tc.tree.nodes[b].neighbors.push_back(a);
  }
  return tc;
}

typedef map<vector<bool>, bool> Visited;
bool dfs(
    const Tree& tree, vector<bool>& coloring,
    const vector<bool>& desired_coloring, Visited& visited)
{
  if (coloring == desired_coloring) return true;
  if (visited[coloring]) return false;
  visited[coloring] = true;

  for (size_t i = 0; i < tree.size; i++)
    for (size_t j : tree.nodes[i].neighbors)
    {
      if (coloring[j] != coloring[i])
      {
        bool c = coloring[j];
        coloring[j] = coloring[i];
        if (dfs(tree, coloring, desired_coloring, visited)) return true;

        coloring[j] = c;
      }
    }

  return false;
}

void solve_test_case(TestCase tc)
{
  Visited v;
  if (dfs(tc.tree, tc.initial_coloring, tc.desired_coloring, v))
    cout << "TAK\n";
  else
    cout << "NIE\n";
}