import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.Char
import Data.List
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import Data.Maybe
main = do
[h,w,rs,cs] <- bsGetLnInts
[n] <- bsGetLnInts
rcs <- replicateM n bsGetLnInts
let dat = abc273dp h w n rcs
[q] <- bsGetLnInts
foldM_ (\rc _ -> do
li <- BS.getLine
let d = BS.index li 0
let Just (l,_) = BS.readInt $ BS.tail $ BS.tail li
let rc1@(r1,c1) = abc273d dat rc d l
putStrLn $ unwords [show r1, show c1]
return rc1
) (rs,cs) [1..q]
bsGetLnInts :: IO [Int]
bsGetLnInts = BS.getLine >>= return . unfoldr (BS.readInt . BS.dropWhile isSpace)
type M = IM.IntMap IS.IntSet
type POS = (Int, Int)
abc273dp :: Int -> Int -> Int -> [[Int]] -> (Int, Int, M, M)
abc273dp h w n rcs = (h, w, rm, cm)
where
rm = sub w [(r, [c]) | (r:c:_) <- rcs]
cm = sub h [(c, [r]) | (r:c:_) <- rcs]
sub ub xyss = fmap (mkset ub) $ IM.fromListWith (++) xyss
mkset ub ys = IS.fromList $ 0 : (succ ub) : ys
abc273d :: (Int, Int, M, M) -> POS -> Char -> Int -> POS
abc273d (h, w, rm, cm) (r, c) d l =
case d of
'L' -> (r, sub decrs rs c)
'R' -> (r, sub incrs rs c)
'U' -> (sub decrs cs r, c)
'D' -> (sub incrs cs r, c)
where
rds = IS.fromAscList [0, succ w] -- row default set
cds = IS.fromAscList [0, succ h] -- column default set
rs = IM.findWithDefault rds r rm
cs = IM.findWithDefault cds c cm
decrs = (IS.lookupLT, succ, (-), max)
incrs = (IS.lookupGT, pred, (+), min)
sub (lkup, sp, op, minmax) s x = minmax (sp $ fromJust $ lkup x s) (op x l)