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
#include <cstdio>
#include <cstring>
#include <map>

#define cont(s) {puts (s); continue;}

int main ()
{
  int t;
  scanf ("%i", &t);
  while (t--)
  {
    int n;
    scanf ("%i", &n);
    char u[n+1], v[n+1];
    scanf (" %s %s", u, v);
    std::multimap <int, int> E;
    for (int i=0; i<n-1; i++)
    {
      int a, b;
      scanf ("%i%i", &a, &b);
      E.emplace (a-1, b-1);
      E.emplace (b-1, a-1);
    }
    if (!strcmp (u, v)) cont ("TAK");
    int c = !!strchr (u, '0') + !!strchr (u, '1');
    int d = !!strchr (v, '0') + !!strchr (v, '1');
    if (c<d)            cont ("NIE");
    if (c==1)           cont (*u==*v? "TAK": "NIE");
    d = 0;
    for (auto e: E) if (v[e.first]==v[e.second]) d = 1;
    if (!d)             cont ("NIE");
    int s = -1, p = -1;
    for (auto e: E)
    {
      if (p==e.first) continue;
      else p = e.first;
      int q = E.count (e.first);
      if (q==1) s = p;
      if (q>2)
      {
        s = -1;
        break;
      }
    }
    if (s==-1)          cont ("TAK");
    p = s;
    c = 0, d = 0;
    while (1)
    {
      auto r = E.equal_range (s);
      auto i = r.first;
      for (; i!=r.second; i++) if (i->second!=p) break;
      if (u[s]!=u[p]) c++;
      if (v[s]!=v[p]) d++;
      if (i==r.second) break;
      p = s;
      s = i->second;
    }
    if (c<d)            cont ("NIE");
    if (c>d)            cont ("TAK");
    if (u[s]!=v[s])     cont ("NIE");
                        cont ("TAK");
  }
  return 0;
}