#include <iostream> #include <vector> using namespace std; vector<vector<int>>g; string s1, s2; bool check(int u, int parent) { for (int v: g[u]) { if (v == parent) continue; if (!check(v, u) || (s2[u-1] == s2[v-1])) return false; } return true; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; cin >> s1 >> s2; g = vector<vector<int>>(n+1, vector<int>(0)); bool path = true; for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); if ((g[u].size() > 2) || (g[v].size() > 2)) path = false; } if (s1 == s2) { cout << "TAK\n"; continue; } if (n == 1) { cout << "NIE\n"; continue; } if (path) { int start = 0; for (int i = 1; i <= n; i++) if (g[i].size() == 1) start = i; int k1 = 1, k2 = 1; int u = g[start][0], v = start; while (1) { if (s1[u-1] != s1[v-1]) k1++; if (s2[u-1] != s2[v-1]) k2++; if (g[u].size() == 1) break; if (g[u][0] != v) { v = u; u = g[u][0]; } else { v = u; u = g[u][1]; } } if (s1[start-1] != s2[start-1]) k1--; if (k1 >= k2) cout << "TAK\n"; else cout << "NIE\n"; continue; } bool both = false; for (int i = 1; i < n; i++) if (s1[i] != s1[i-1]) both = true; if (both && (!check(1, 0))) cout << "TAK\n"; else cout << "NIE\n"; } }
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 | #include <iostream> #include <vector> using namespace std; vector<vector<int>>g; string s1, s2; bool check(int u, int parent) { for (int v: g[u]) { if (v == parent) continue; if (!check(v, u) || (s2[u-1] == s2[v-1])) return false; } return true; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; cin >> s1 >> s2; g = vector<vector<int>>(n+1, vector<int>(0)); bool path = true; for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; g[u].push_back(v); g[v].push_back(u); if ((g[u].size() > 2) || (g[v].size() > 2)) path = false; } if (s1 == s2) { cout << "TAK\n"; continue; } if (n == 1) { cout << "NIE\n"; continue; } if (path) { int start = 0; for (int i = 1; i <= n; i++) if (g[i].size() == 1) start = i; int k1 = 1, k2 = 1; int u = g[start][0], v = start; while (1) { if (s1[u-1] != s1[v-1]) k1++; if (s2[u-1] != s2[v-1]) k2++; if (g[u].size() == 1) break; if (g[u][0] != v) { v = u; u = g[u][0]; } else { v = u; u = g[u][1]; } } if (s1[start-1] != s2[start-1]) k1--; if (k1 >= k2) cout << "TAK\n"; else cout << "NIE\n"; continue; } bool both = false; for (int i = 1; i < n; i++) if (s1[i] != s1[i-1]) both = true; if (both && (!check(1, 0))) cout << "TAK\n"; else cout << "NIE\n"; } } |