#include <bits/stdc++.h>
using namespace std;
const int limit = 100010;
set <int> st[limit];
vector <int> v[limit];
bitset <limit> vs;
string now, goal;
bool dfs(int x, char k) {
bool ok = 0;
if (k == now[x - 1])
return 1;
vs[x] = 1;
for (auto &e:st[x]) {
if (!vs[e]) {
ok = dfs(e, k);
if (ok) {
now[x - 1] = k;
break;
}
}
}
for (int i = 0; !ok && i < v[x].size(); i++) {
if (now[v[x][i] - 1] == k) {
ok = 1;
now[x] = k;
}
}
vs[x] = 0;
return ok;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
int N, a, b;
queue <int> rozp;
cin >> t;
for (int i = 0; i < t; i++) {
cin >> N;
cin >> now >> goal;
bool result = 1;
for (int z = 1; z <= N; z++) {
st[i].clear();
v[i].clear();
}
for (int z = 1; z < N; z++) {
cin >> a >> b;
st[a].insert(b);
st[b].insert(a);
}
for (int z = 1; z <= N; z++) {
if (st[z].size() == 1)
rozp.push(z);
}
while (!rozp.empty()) {
a = rozp.front();
rozp.pop();
result &= dfs(a, goal[a - 1]);
if (!st[a].empty()) {
int e = *st[a].begin();
st[e].erase(a);
st[a].erase(e);
v[e].push_back(a);
v[a].push_back(e);
if (st[e].size() == 1)
rozp.push(e);
}
}
cout << (result ? "TAK\n" : "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 80 81 82 83 84 | #include <bits/stdc++.h> using namespace std; const int limit = 100010; set <int> st[limit]; vector <int> v[limit]; bitset <limit> vs; string now, goal; bool dfs(int x, char k) { bool ok = 0; if (k == now[x - 1]) return 1; vs[x] = 1; for (auto &e:st[x]) { if (!vs[e]) { ok = dfs(e, k); if (ok) { now[x - 1] = k; break; } } } for (int i = 0; !ok && i < v[x].size(); i++) { if (now[v[x][i] - 1] == k) { ok = 1; now[x] = k; } } vs[x] = 0; return ok; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; int N, a, b; queue <int> rozp; cin >> t; for (int i = 0; i < t; i++) { cin >> N; cin >> now >> goal; bool result = 1; for (int z = 1; z <= N; z++) { st[i].clear(); v[i].clear(); } for (int z = 1; z < N; z++) { cin >> a >> b; st[a].insert(b); st[b].insert(a); } for (int z = 1; z <= N; z++) { if (st[z].size() == 1) rozp.push(z); } while (!rozp.empty()) { a = rozp.front(); rozp.pop(); result &= dfs(a, goal[a - 1]); if (!st[a].empty()) { int e = *st[a].begin(); st[e].erase(a); st[a].erase(e); v[e].push_back(a); v[a].push_back(e); if (st[e].size() == 1) rozp.push(e); } } cout << (result ? "TAK\n" : "NIE\n"); } } |
English