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
 95
 96
 97
 98
 99
100
101
102
103
#include <stdio.h>
#include <string>
#include <vector>
#include <set>
#include <string.h>

using std::string;
using std::vector;
using std::pair;
using std::make_pair;
using std::set;

const int max_size = 1e5;

int n;
char start_coding[max_size+1];        
char end_coding[max_size+1];
vector<pair<int, int>> trees_edges;

bool one_color()
{
    for (int i = 1; i < n; i++)
        if (start_coding[i] != start_coding[i-1])
            return false;
    return true;
}

bool linia_wynik;

bool linia()
{
    int start_segments = 0;
    int end_segments = 0;
    static int neighbours[max_size];
    
    for (int i = 0; i < n; i++)
        neighbours[i] = 0;
    for (auto v : trees_edges)
    {
        neighbours[v.first]++;
        neighbours[v.second]++;
        
        if (start_coding[v.first] != start_coding[v.second])
            start_segments++;
        if (end_coding[v.first] != end_coding[v.second])
            end_segments++;
    }
    
    for (int i = 0; i < n; i++)
    {
        if (neighbours[i] > 2)
            return false;
        if (neighbours[i] == 1)
            if (start_coding[i] != end_coding[i])
                start_segments--;
    }
    
    linia_wynik = (start_segments >= end_segments);
    
    return true;
}

bool bipartite()
{
    for (auto p : trees_edges)
        if (end_coding[p.first] == end_coding[p.second])
            return false;
    return true;
}

int main()
{
    int T;
    
    scanf("%d", &T);
    
    while(T--)
    {
        trees_edges.clear();
        
        scanf("%d%s%s", &n, start_coding, end_coding);
        for (int i = 1; i < n; i++)
        {
            int a, b;
            scanf("%d%d", &a, &b);
            
            trees_edges.push_back(make_pair(a-1, b-1));
        }
        
        if (strcmp(start_coding, end_coding) == 0)
            printf("TAK\n");
        else if (one_color())
            printf("NIE\n");
        else if (linia())
            printf(linia_wynik ? "TAK\n" : "NIE\n");
        else if (bipartite())
            printf("NIE\n");
        else
            printf("TAK\n");
    }
    
    return 0;
}