History Cleanable DFA

No attempts yetTime limit2sMemory limit512 MB

Problem

A deterministic finite automaton (DFA) is a finite state machine that accepts or rejects finite input strings. The figure above draws one DFA as a state diagram. This automaton has three states S0S_0, S1S_1 and S2S_2, drawn as circles, and it reads a finite sequence of 0s and 1s as input. Every state has one outgoing arrow for 0 and one outgoing arrow for 1, so on reading a symbol the automaton moves from its current state to the state that arrow points at. If the automaton is in state S0S_0 and the current symbol is 1, it moves to S1S_1, written δ(S0,1)=S1\delta(S_0, 1) = S_1. Extending the notation to whole strings gives statements such as δ(S0,10)=S2\delta(S_0, 10) = S_2 and δ(S1,011010)=S0\delta(S_1, 011010) = S_0.

A DFA has a start state, drawn as an arrow coming in from nowhere, and a set of accept states, drawn as double circles. A DFA with start state q0q_0 accepts a string ww if and only if δ(q0,w)\delta(q_0, w) is an accept state. In the figure above S0S_0 is both the start state and an accept state, and that DFA accepts exactly the binary numbers that are multiples of 3, the empty string included.

Now take a DFA DD with states S0,S1,,Sn1S_0, S_1, \dots, S_{n-1}. A string ww is a history cleaner for DD if δ(Si,w)=δ(Sj,w)\delta(S_i, w) = \delta(S_j, w) holds for all i,j{0,,n1}i, j \in \{0, \dots, n-1\}. In other words, whichever state the run starts from, reading ww leaves the DFA in one common state. DD is history cleanable if a history cleaner exists for it. Given a DFA whose input is a sequence of 0s and 1s, decide whether it is history cleanable.

Input

The first line contains one integer tt, the number of test cases (1t5001 \le t \le 500). Each test case starts with a line holding one integer nn, the number of states of a DFA with states S0,S1,,Sn1S_0, S_1, \dots, S_{n-1} (2n5002 \le n \le 500). The second line of the test case holds nn space separated integers a0,a1,,an1a_0, a_1, \dots, a_{n-1} and the third line holds nn space separated integers b0,b1,,bn1b_0, b_1, \dots, b_{n-1} (0ai,bi<n0 \le a_i, b_i < n), which means δ(Si,0)=Sai\delta(S_i, 0) = S_{a_i} and δ(Si,1)=Sbi\delta(S_i, 1) = S_{b_i} for every ii with 0i<n0 \le i < n.

Output

For each test case print one line with the answer for that DFA. Print YES if it is history cleanable, and NO otherwise.