import List main@m=getLine>>=putStrLn.(\[x,y]->f y x).words>>m f l=map(l!!).take(length l).tail.iterate(maybe 0id.(`lookup`(zip[0..]$map snd$sort$zip l[0..]))).read
Note that non-ascii characters in the above source code will be escaped (such as \x9f).