Import java.util.EmptyStackException;
Import java.util.LinkedList;
Import Java.util.Queue;
Import Java.util.Scanner;
Import Java.util.Stack;
public class H06 {
/**
* @return
* @ given a positive integer N represents the number of trains, 0<n<10, then enter the train inbound sequence,
* Altogether n trains, each train with number 1-9 numbered.
* The serial number of the outbound train output is required in dictionary order.
*
Ideas
* To pit the train into the queue, row the front of the advanced
* Station is a stack, backward, first out
* Outbound trains can be simply stored in string
* When the station queue and the train stack are empty, the train all play, print out the sequence
* Taking into account the dictionary order, when a car can play, prioritize outbound, and then recursion
* When a car can get in, get in, and then pass the result.
*
* The recursion of the subject with TMP protected the scene
*/
public static void Main (string[] args)
{
Scanner cin = new Scanner (system.in);
int Num=cin.nextint ();
queue<integer> qtoin = new linkedlist<integer> ();
for (int i = 0; i<num; i++)
{
Qtoin.add (Cin.nextint ());
}
Cin. Close ();
stack<integer> stoout = new stack<integer> ();
String out = "";
Stationdispatch (qtoin,stoout,out);
}
public static void Stationdispatch (Queue<integer> qtoin,
Stack<integer> stoout,string out)
{
Boolean hasqtoin = true;
Boolean hasstoout = true;
if (qtoin.peek () = = null)
{
Hasqtoin = false;
}
Try
{
Stoout.peek ();
} catch (Emptystackexception e)
{
Hasstoout = false;
}
if (! Hasqtoin &&! hasstoout)
{
System.out.println (out);
Return
}
if (hasstoout)
{
queue<integer> qtointmp = new linkedlist<integer> (qtoin);
Stack<integer> stoouttmp = (stack<integer>) stoout.clone ();
String outtmp=out;
Outtmp + = Stoouttmp.pop (). toString ();
Stationdispatch (QTOINTMP,STOOUTTMP,OUTTMP);
}
if (Hasqtoin)
{
queue<integer> qtointmp = new linkedlist<integer> (qtoin);
Stack<integer> stoouttmp = (stack<integer>) stoout.clone ();
String outtmp=out;
Stoouttmp.push (Qtointmp.poll ());
Stationdispatch (QTOINTMP,STOOUTTMP,OUTTMP);
}
}
}
Train Pit Stop problem