public class DFA {
private State [] machine;
private int N;
public DFA(In in){
int N = in.readInt();
machine = new State[N];
for (int i = 0; i < N; i++)
{
String type = in.readString();
int next0 = in.readInt();
int next1 = in.readInt();
machine[i] = new State (type, next0, next1);
}
}
public String run( String input)
{
int count = input.length();
int stateNum = 0;
for (int i = 0; i < count; i++) {
stateNum = machine[stateNum].next(input.charAt(i));
}
return machine[stateNum].type();
}
public String toString()
{
String s = "";
for (int j = 0; j < machine.length; j++)
s += machine[j] .type() + " " + machine[j] .next('0') + " " +
machine[j] .next('1');
s += '\n';
return s;
}
public static void main(String[] args)
{
In in = new In(args[0] );
DFA dfa = new DFA (in);
System.out.println(dfa);
while (!StdIn.isEmpty())
{
String input = StdIn.readString();
StdOut.println(dfa.run(input));
}
}
}