History Cleanable DFA
InterviewTime limit2sMemory limit512 MB
Given a binary DFA, decide whether some input string drives every state to one common state.
- Level
Medium6 of 10
- Topics
- Graph, BFS, Implementation
- Solved
- No attempts yet
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 , and , 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 and the current symbol is 1, it moves to , written . Extending the notation to whole strings gives statements such as and .
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 accepts a string if and only if is an accept state. In the figure above 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 with states . A string is a history cleaner for if holds for all . In other words, whichever state the run starts from, reading leaves the DFA in one common state. 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 , the number of test cases (). Each test case starts with a line holding one integer , the number of states of a DFA with states (). The second line of the test case holds space separated integers and the third line holds space separated integers (), which means and for every with .
Output
For each test case print one line with the answer for that DFA. Print YES if it is history cleanable, and NO otherwise.