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
#include <cstdio>
#include <vector>

#define MAXN 100100

char from[MAXN];
char to[MAXN];

int N;
int T;

std::vector<int> nei[MAXN];

void solvePath() {
  // Find one end of the path;
  int leaf = 0;
  for (int i = 0; i < N; ++i) if (nei[i].size() == 1) leaf = i;
  int fromsegs = 0;
  int tosegs = 0;
  int prev = -1;
  int cur = leaf;
  do {
    int newleaf = nei[cur][0];
    if (newleaf == prev) newleaf = nei[cur][1];
    prev = cur;
    cur = newleaf;
    if (from[prev] != from[cur]) fromsegs++;
    if (to[prev] != to[cur]) tosegs++; 
  } while (nei[cur].size() == 2); 
  if (from[leaf] != to[leaf]) tosegs += 1;
  printf("%s", (fromsegs < tosegs) ? "NIE\n" : "TAK\n");
}

void solve() {
  scanf("%d\n", &N);
  scanf("%s\n%s\n", from, to);
  for (int i = 0; i < N - 1; ++i) {
    int a, b;
    scanf("%d %d", &a, &b);
    nei[a-1].push_back(b-1);
    nei[b-1].push_back(a-1);
  } 
  // First test. Are the two strings equal?
  bool equal = true;
  for (int i = 0; i < N; ++i) if (from[i] != to[i]) equal = false;
  if (equal) { printf("TAK\n"); return; }
  // Second test. Are both colors present in the source?
  bool absent = true;
  for (int i = 0; i < N; ++i) if (from[i] != from[0]) absent = false;
  if (absent) { printf("NIE\n"); return; }
  // Search for a vertex of degree three or more.
  bool path = true;
  for (int i = 0; i < N; ++i) if (nei[i].size() > 2) path = false;
  if (path) { solvePath(); return; }
  // Search for two adjacent vertices of the same color.
  bool alternating = true;
  for (int i = 0; i < N; ++i) for (int n : nei[i]) if (to[i] == to[n]) alternating = false;
  if (alternating) { printf("NIE\n"); return; }
  printf("TAK\n"); return;
}

int main() {
  scanf("%d", &T);
  for (int ___t = 0; ___t < T; ++___t) {
    solve();
    for (int i = 0; i < N; ++i) nei[i].resize(0);
  }
}