#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define rep(a, b) for(int a = 0; a < (b); ++a)
#define st first
#define nd second
#define pb push_back
#define all(a) a.begin(), a.end()
const int LIM=1e5+7;
vector<int>V[LIM];
int ile[2][2];
string A, B;
char lsta, lstb;
bool ok;
void DFS(int x, int o) {
if(lsta!=A[x]) ++ile[0][A[x]-'0'];
if(lstb!=B[x]) ++ile[1][B[x]-'0'];
lsta=A[x];
lstb=B[x];
for(auto i : V[x]) if(i!=o) {
if(B[x]==B[i]) ok=true;
DFS(i, x);
}
}
void solve() {
int n;
cin >> n >> A >> B;
rep(i, n) V[i].clear();
rep(i, n-1) {
int a, b;
cin >> a >> b; --a; --b;
V[a].pb(b);
V[b].pb(a);
}
if(A==B) {
cout << "TAK\n";
return;
}
int x=0, y=0;
rep(i, n) {
if(A[i]=='0') x|=1; else x|=2;
if(B[i]=='0') y|=1; else y|=2;
}
if((x|y)>x) {
cout << "NIE\n";
return;
}
int ma=0;
x=0;
rep(i, n) {
if(V[i].size()==1) x=i;
ma=max(ma, int(V[i].size()));
}
lsta=lstb='2';
rep(i, 2) rep(j, 2) ile[i][j]=0;
ok=false;
DFS(x, x);
if(ma>2) {
cout << (ok?"TAK":"NIE") << '\n';
return;
}
if(A[x]!=B[x]) --ile[0][A[x]-'0'];
cout << (ile[0][0]>=ile[1][0]&&ile[0][1]>=ile[1][1]?"TAK":"NIE") << '\n';
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
int _;
cin >> _;
while(_--) solve();
}
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 | #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define rep(a, b) for(int a = 0; a < (b); ++a) #define st first #define nd second #define pb push_back #define all(a) a.begin(), a.end() const int LIM=1e5+7; vector<int>V[LIM]; int ile[2][2]; string A, B; char lsta, lstb; bool ok; void DFS(int x, int o) { if(lsta!=A[x]) ++ile[0][A[x]-'0']; if(lstb!=B[x]) ++ile[1][B[x]-'0']; lsta=A[x]; lstb=B[x]; for(auto i : V[x]) if(i!=o) { if(B[x]==B[i]) ok=true; DFS(i, x); } } void solve() { int n; cin >> n >> A >> B; rep(i, n) V[i].clear(); rep(i, n-1) { int a, b; cin >> a >> b; --a; --b; V[a].pb(b); V[b].pb(a); } if(A==B) { cout << "TAK\n"; return; } int x=0, y=0; rep(i, n) { if(A[i]=='0') x|=1; else x|=2; if(B[i]=='0') y|=1; else y|=2; } if((x|y)>x) { cout << "NIE\n"; return; } int ma=0; x=0; rep(i, n) { if(V[i].size()==1) x=i; ma=max(ma, int(V[i].size())); } lsta=lstb='2'; rep(i, 2) rep(j, 2) ile[i][j]=0; ok=false; DFS(x, x); if(ma>2) { cout << (ok?"TAK":"NIE") << '\n'; return; } if(A[x]!=B[x]) --ile[0][A[x]-'0']; cout << (ile[0][0]>=ile[1][0]&&ile[0][1]>=ile[1][1]?"TAK":"NIE") << '\n'; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int _; cin >> _; while(_--) solve(); } |
English