There are $$$n$$$ points on an infinite plane. The $$$i$$$-th point has coordinates $$$(x_i, y_i)$$$ such that $$$x_i > 0$$$ and $$$y_i > 0$$$. The coordinates are not necessarily integer.In one move you perform the following operations:   choose two points $$$a$$$ and $$$b$$$ ($$$a \neq b$$$);  move point $$$a$$$ from $$$(x_a, y_a)$$$ to either $$$(x_a + 1, y_a)$$$ or $$$(x_a, y_a + 1)$$$;  move point $$$b$$$ from $$$(x_b, y_b)$$$ to either $$$(x_b + 1, y_b)$$$ or $$$(x_b, y_b + 1)$$$;  remove points $$$a$$$ and $$$b$$$. However, the move can only be performed if there exists a line that passes through the new coordinates of $$$a$$$, new coordinates of $$$b$$$ and $$$(0, 0)$$$. Otherwise, the move can't be performed and the points stay at their original coordinates $$$(x_a, y_a)$$$ and $$$(x_b, y_b)$$$, respectively.The numeration of points does not change after some points are removed. Once the points are removed, they can't be chosen in any later moves. Note that you have to move both points during the move, you can't leave them at their original coordinates.What is the maximum number of moves you can perform? What are these moves?If there are multiple answers, you can print any of them.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The $$$i$$$-th of the next $$$n$$$ lines contains four integers $$$a_i, b_i, c_i, d_i$$$ ($$$1 \le a_i, b_i, c_i, d_i \le 10^9$$$). The coordinates of the $$$i$$$-th point are $$$x_i = \frac{a_i}{b_i}$$$ and $$$y_i = \frac{c_i}{d_i}$$$.

In the first line print a single integer $$$c$$$ — the maximum number of moves you can perform. Each of the next $$$c$$$ lines should contain a description of a move: two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le n$$$, $$$a \neq b$$$) — the points that are removed during the current move. There should be a way to move points $$$a$$$ and $$$b$$$ according to the statement so that there's a line that passes through the new coordinates of $$$a$$$, the new coordinates of $$$b$$$ and $$$(0, 0)$$$. No removed point can be chosen in a later move. If there are multiple answers, you can print any of them. You can print the moves and the points in the move in the arbitrary order.

NoteHere are the points and the moves for the ones that get chosen for the moves from the first example:

import Control.Monad
import Data.Maybe
import Data.Int
import Data.List
import Data.Array.IO
import Data.Array.Base
import Data.IORef
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import System.IO

parseInt :: C.ByteString -> Int
parseInt = fst . fromJust . C.readInt

main :: IO ()
main = do
  m <- fmap parseInt C.getLine
  let norm (x, y) = let g = gcd x y :: Int64 in (x `quot` g, y `quot` g)
      getInput xs i = do
        [a, b, c, d] <- map (fromIntegral . parseInt) . C.words <$> C.getLine
        let u = norm (a * d + b * d, b * c)
            v = norm (a * d, b * c + b * d)
        return ((u, i) : (v, i) : xs)
  e <- newArray (0, 2 * m) [] :: IO (IOArray Int [(Int, Int)])
  let buildGraph = do
        ts <- foldM getInput [] [1..m]
        t <- newArray (0, m) 0 :: IO (IOUArray Int Int)
        let acc (pr, n) (r, i) = do
              let n' = if pr == r then n else n + 1
              v <- unsafeRead t i
              if v == 0 then unsafeWrite t i n' else do
                add i n' v
                add i v n'
              return (r, n')
            add :: Int -> Int -> Int -> IO ()
            add i u v = do
              vs <- unsafeRead e u
              unsafeWrite e u ((i, v) : vs)
        (_, n') <- foldM acc ((0, 0), 0) $ sort ts
        return n'
  n <- buildGraph
  es <- newArray (0, m) False :: IO (IOUArray Int Bool)
  vs <- newArray (0, n) False :: IO (IOUArray Int Bool)
  ps <- newArray (0, n) 0 :: IO (IOUArray Int Int)
  resultNum <- newIORef (0 :: Int)
  results <- newIORef ([] :: [(Int, Int)])
  let prep x u = do
        y <- unsafeRead ps u
        if y == 0 then unsafeWrite ps u x else do
          unsafeWrite ps u 0
          modifyIORef' results ((x, y):)
          modifyIORef' resultNum (+1)
      dfs u = do
        f0 <- unsafeRead vs u
        if f0 then return False else do
          unsafeWrite vs u True
          vs' <- unsafeRead e u
          foldM acc False vs'
        where acc f (i, v) = do
                f1 <- unsafeRead es i
                if f1 then return f else do
                  unsafeWrite es i True
                  f2 <- dfs v
                  if f2 then prep i v >> return f
                        else prep i u >> return (not f)
  forM_ [1..n] dfs
  num <- readIORef resultNum
  as <- readIORef results
  hPutBuilder stdout $ intDec num `mappend` charUtf8 '\n'
  let render (a, b) = intDec a `mappend` charUtf8 ' ' `mappend` intDec b
  hPutBuilder stdout $ mconcat $ map (`mappend` charUtf8 '\n') $ map render as

import Control.Monad
import Data.Maybe
import Data.Int
import Data.List
import qualified Data.Array as A
import Data.Array.IO
import Data.Array.Base
import Data.IORef
import qualified Data.ByteString.Char8 as C
import qualified Data.Map.Strict as M
import Text.Printf

parseInt :: C.ByteString -> Int
parseInt = fst . fromJust . C.readInt

main :: IO ()
main = do
  m <- fmap parseInt C.getLine
  let norm (x, y) = let g = gcd x y :: Int64 in (x `quot` g, y `quot` g)
      getInput (rs, ts) i = do
        [a, b, c, d] <- map (fromIntegral . parseInt) . C.words <$> C.getLine
        let u = norm (a * d + b * d, b * c)
            v = norm (a * d, b * c + b * d)
        return (u : v : rs, (i, u, v) : ts)
  (rs, ts) <- foldM getInput ([], []) [1..m]
  let uniq [] = []
      uniq [x] = [x]
      uniq (x1 : x2 : xs) = if x1 == x2 then uniq (x2 : xs) else x1 : uniq (x2 : xs)
      mp = M.fromAscList $ zip (uniq $ sort rs) [1..]
      n = M.size mp
      edges = foldl' acc [] ts
        where acc es (i, u, v) = (u', (i, v')) : (v', (i, u')) : es
                where u' = mp M.! u
                      v' = mp M.! v
      e = A.accumArray (flip (:)) [] (1, n) edges
  putStrLn $ show e
  es <- newArray (0, m) False :: IO (IOUArray Int Bool)
  vs <- newArray (0, n) False :: IO (IOUArray Int Bool)
  ps <- newArray (0, n) Nothing :: IO (IOArray Int (Maybe Int))
  resultNum <- newIORef (0 :: Int)
  results <- newIORef ([] :: [(Int, Int)])
  let prep x u = do
        val <- unsafeRead ps u
        case val of
          Nothing -> unsafeWrite ps u (Just x)
          Just y -> do
            unsafeWrite ps u Nothing
            modifyIORef' results ((x, y):)
            modifyIORef' resultNum (+1)
      dfs u = do
        f0 <- unsafeRead vs u
        if f0 then return False else do
          unsafeWrite vs u True
          foldM acc False (e A.! u)
        where acc f (i, v) = do
                f1 <- unsafeRead es i
                if f1 then return f else do
                  unsafeWrite es i True
                  f2 <- dfs v
                  if f2 then prep i v >> return f
                        else prep i u >> return (not f)
  forM_ [1..n] dfs
  num <- readIORef resultNum
  as <- readIORef results
  C.putStrLn $ C.pack $ show num
  forM_ as $ \(a, b) -> C.putStrLn $ C.pack $ printf "%d %d" a b


Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.

In first line there is one integer n (1 ≤ n ≤ 2·105) — number of cafes indices written by Vlad. In second line, n numbers a1, a2, ..., an (0 ≤ ai ≤ 2·105) are written — indices of cafes in order of being visited by Vlad. Vlad could visit some cafes more than once. Note that in numeration, some indices could be omitted.

Print one integer — index of the cafe that Vlad hasn't visited for as long as possible.

NoteIn first test, there are three cafes, and the last visits to cafes with indices 1 and 2 were after the last visit to cafe with index 3; so this cafe is the answer. In second test case, there are also three cafes, but with indices 1, 2 and 4. Cafes with indices 1 and 4 were visited after the last visit of cafe with index 2, so the answer is 2. Note that Vlad could omit some numbers while numerating the cafes.

import qualified Data.Map.Strict as M
import qualified Data.ByteString.Char8 as B
import Control.Applicative
import Data.List
import Data.Function
import Data.Maybe

f _ m [] = fst $ minimumBy (compare `on` snd) $ M.assocs m
f i m (a:as) = f (i+1) (M.alter (\_ -> Just i) a m) as

main = do
    n <- readLn :: IO Int
    as <- map (fst . fromJust . B.readInt ) . B.words <$> B.getLine
    let b = f 0 M.empty as
    print b

import qualified Data.Map as M
import Control.Applicative
import Data.List
import Data.Function

f _ m [] = fst $ minimumBy (compare `on` snd) $ M.assocs m
f i m (a:as) = f (i+1) (M.alter (\_ -> Just i) a m) as

main = do
    n <- readLn :: IO Int
    as <- map (read :: String -> Int ) . words <$> getLine
    let b = f 0 M.empty as
    print b

import qualified Data.IntMap as M
import Data.List
import Data.Function
main = getLine >> getLine >>= print . fst . minimumBy (compare `on` snd) . M.assocs . foldl' (\m (i, c) -> M.insert c i m) M.empty . zip [1..] . map read . words

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU
{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString.Char8 as C
import qualified Data.IntMap as I
import Data.List (foldl')
import Data.Maybe

readI = fst . fromJust . C.readInt

main = C.interact $ C.pack . solve . map readI . C.words

solve (n:xs) = show $ ans
    where
        ans = snd $ minimum $ I.elems mp
        ys = zip [0..] xs
        mp = foldl' f I.empty ys
        f m v@(_,k) = I.insert k v m


Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from $$$(0,0)$$$ to $$$(x,0)$$$ by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its $$$n$$$ favorite numbers: $$$a_1, a_2, \ldots, a_n$$$. What is the minimum number of hops Rabbit needs to get from $$$(0,0)$$$ to $$$(x,0)$$$? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points $$$(x_i, y_i)$$$ and $$$(x_j, y_j)$$$ is $$$\sqrt{(x_i-x_j)^2+(y_i-y_j)^2}$$$.For example, if Rabbit has favorite numbers $$$1$$$ and $$$3$$$ he could hop from $$$(0,0)$$$ to $$$(4,0)$$$ in two hops as shown below. Note that there also exists other valid ways to hop to $$$(4,0)$$$ in $$$2$$$ hops (e.g. $$$(0,0)$$$ $$$\rightarrow$$$ $$$(2,-\sqrt{5})$$$ $$$\rightarrow$$$ $$$(4,0)$$$).    Here is a graphic for the first example. Both hops have distance $$$3$$$, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number $$$a_i$$$ and hops with distance equal to $$$a_i$$$ in any direction he wants. The same number can be used multiple times.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. Next $$$2t$$$ lines contain test cases — two lines per test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le x \le 10^9$$$)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct. It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$10^5$$$.

For each test case, print a single integer — the minimum number of hops needed.

NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to $$$(2,\sqrt{5})$$$, then to $$$(4,0)$$$ for a total of two hops. Each hop has a distance of $$$3$$$, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop $$$3$$$ times is: $$$(0,0)$$$ $$$\rightarrow$$$ $$$(4,0)$$$ $$$\rightarrow$$$ $$$(8,0)$$$ $$$\rightarrow$$$ $$$(12,0)$$$.In the third test case of the sample, Rabbit can hop from $$$(0,0)$$$ to $$$(5,0)$$$.In the fourth test case of the sample, Rabbit can hop: $$$(0,0)$$$ $$$\rightarrow$$$ $$$(5,10\sqrt{2})$$$ $$$\rightarrow$$$ $$$(10,0)$$$.

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}

main = getLine >>= test.read
test :: Integer -> IO ()
test 0 = return ()
test t = do
  (n:x:_) <- map read.words <$> getLine
  as <- map read.words <$> getLine
  let m = maximum as
  print (if any (== x) as then 1 else max 2 $ div x m + fromEnum (mod x m /= 0))
  test (t - 1)

import Control.Monad
import Data.Ratio
main :: IO ()
main = do
  n <- readLn
  replicateM_ n routine

routine :: IO ()
routine = do
  [_,x] <- (map read.words) <$> getLine
  l <- (map read.words) <$> getLine
  print $ solve x l

solve :: Int -> [Int] -> Int
solve x l
  | x `elem` l = 1
  |otherwise = max 2 (ceiling (x % max1))
  where
    max1 = maximum l

{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import Data.Ord
import Data.Int
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if s then
                aux s
            else
                return id
        else
            liftM ((.) $ showChar x) $ aux False
    in liftM (flip ($) []) $ aux True

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

class IOInteract a where
    convertEither :: String -> Either String a
    toShowS :: a -> String -> String
    toShow :: a -> String
    toShow x = toShowS x []

instance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where
    convertEither = convertEitherp (undefined :: flag)
    toShowS = toShowSp (undefined :: flag)

type family IOType x where
    IOType String = HString
    IOType [x] = HList
    IOType x = HNormal

class IOInteractp flag a where
    convertEitherp :: flag -> String -> Either String a
    toShowSp :: flag -> a -> String -> String

instance (Show a, Read a) => IOInteractp HNormal a where
    convertEitherp _ x = readEither x
    toShowSp _ x = shows x

instance IOInteractp HString String where
    convertEitherp _ x = Right x
    toShowSp _ x = showString x

instance (IOInteract a) => IOInteractp HList [a] where
    convertEitherp _ x = mapM convertEither $ words x
    toShowSp _ [] = id
    toShowSp _ (x : []) = toShowS x
    toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toShow

main :: IO ()
main = do
    o <- runExceptT main_
    case o of
        Right () -> return ()
        Left s -> putStrLn s

main_ :: EIO ()
-- template --
main_ = do
    t <- get
    replicateM_ t f1

f1 :: EIO ()
f1 = do
    (n, x) <- liftM2 (,) get get
    as <- replicateM n get
    putln $ f2 as x

f2 :: [Int64] -> Int64 -> Int64
f2 as x = minimum $ fmap (\k -> if (mod x k) == 0 then (div x k) else max (div (x + k - 1) k) 2) as

import Control.Monad

doit :: IO ()
doit = do
  [_, x] <- fmap (map read . words) getLine
  tmp <- fmap (map read . words) getLine
  print $ if x `elem` tmp then 1 else
          let y = maximum tmp
          in 2 `max` ((x + y - 1) `div` y)

main = readLn >>= flip replicateM_ doit

{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import Data.Ord
import Data.Int
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if s then
                aux s
            else
                return id
        else
            liftM ((.) $ showChar x) $ aux False
    in liftM (flip ($) []) $ aux True

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

class IOInteract a where
    convertEither :: String -> Either String a
    toShowS :: a -> String -> String
    toShow :: a -> String
    toShow x = toShowS x []

instance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where
    convertEither = convertEitherp (undefined :: flag)
    toShowS = toShowSp (undefined :: flag)

type family IOType x where
    IOType String = HString
    IOType [x] = HList
    IOType x = HNormal

class IOInteractp flag a where
    convertEitherp :: flag -> String -> Either String a
    toShowSp :: flag -> a -> String -> String

instance (Show a, Read a) => IOInteractp HNormal a where
    convertEitherp _ x = readEither x
    toShowSp _ x = shows x

instance IOInteractp HString String where
    convertEitherp _ x = Right x
    toShowSp _ x = showString x

instance (IOInteract a) => IOInteractp HList [a] where
    convertEitherp _ x = mapM convertEither $ words x
    toShowSp _ [] = id
    toShowSp _ (x : []) = toShowS x
    toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toShow

main :: IO ()
main = do
    o <- runExceptT main_
    case o of
        Right () -> return ()
        Left s -> putStrLn s

main_ :: EIO ()
-- template --
main_ = do
    t <- get
    replicateM_ t f1

f1 :: EIO ()
f1 = do
    (n, x) <- liftM2 (,) get get
    as <- replicateM n get
    putln $ f2 as x

f2 :: [Int64] -> Int64 -> Int64
f2 as x =   let k = maximum as
            in
            if (mod x k) == 0 then (div x k) else max (div (x + k - 1) k) 2


Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents that the kth destination is at distance ak kilometers from the starting point. No two destinations are located in the same place. Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination. The distance between destination located at kilometer x and next destination, located at kilometer y, is |x - y| kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all n destinations and he doesn't visit a destination more than once. Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.

The first line contains integer n (2 ≤ n ≤ 105). Next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 107).

Output two integers — the numerator and denominator of a fraction which is equal to the wanted average number. The fraction must be irreducible.

import Data.List
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

main :: IO()
main = putStrLn . unwords . map show . solve . map (fst . fromJust . C.readInteger) . C.words =<< B.getContents

solve :: [Integer] -> [Integer]
solve (n:a) = let sorted = sort a
                  relativeDist = sum $ calcRelativeDist 1 (head sorted) 0 (tail sorted)
                  absoluteDist = sum a
                  totalDist = 2 * relativeDist + absoluteDist
                  common = gcd totalDist n
              in  [div totalDist common, div n common]

calcRelativeDist :: Integer -> Integer -> Integer -> [Integer] -> [Integer]
calcRelativeDist i last dist []    = [dist]
calcRelativeDist i last dist (a:s) = dist : calcRelativeDist (i + 1) a (dist + i * (a - last)) s

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Ratio
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

casti = fromIntegral

main = do
    n <- readInt <$> B.getLine
    l <- map readInt . B.words <$> B.getLine
    let r = solve n l
    putStrLn $ show (numerator r) ++ " "++ show (denominator r)

solve :: Int -> [Int] -> Rational
solve n l = foldl' f s1 (zip3 (tail l') sums [1..])
    where
    l' = map casti (sort l)
    sums = scanl1 (+) $ zipWith (*) l' [ 4*i-1 | i <- [1..]]
    s1 = head l'
    f a (b,s,n) = a +( (2*n+1)*b - s/n) / (n+1)

import Data.List (sort)
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import Control.Applicative (liftA, (<$>))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Ratio (Ratio, (%), numerator, denominator)

solve :: Integer -> [Integer] -> Ratio Integer
solve n a = inc + sum out
    where
    dist = zipWith (-) (tail a) a :: [Integer]
    out = zipWith (\d k -> 2 * k * (n - k) * d % n) dist [1..]
    inc = sum $ (% n) <$> a :: Ratio Integer

wrap :: Int -> [Int] -> [String]
wrap n a = [show i, " ", show j]
    where
    out = solve (fromIntegral n) (fromIntegral <$> sort a) :: Ratio Integer
    [i, j] = ($ out) <$> [numerator, denominator] :: [Integer]

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = parse <$> B.getLine >>= \[n] -> parse <$> B.getLine >>= \a ->
    mapM_ putStr $ wrap n a

import Data.Int (Int64)
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Control.Applicative (liftA, (<$>))
import qualified Data.ByteString.Char8 as C
import Data.Ratio (Ratio, (%), numerator, denominator)

solve :: Int64 -> [Int64] -> Ratio Int64
solve n a = (sum a + x + y) % n
    where
    x = (2*) . sum . zipWith (\i j -> (2 * i + 1 - n) * j) [1..n - 2] $ tail a
    y = 2 * (n - 1) * (last a - head a)

wrap :: Int -> [Int] -> [String]
wrap n a = [show i, " ", show j]
    where
    out = solve (fromIntegral n) (fromIntegral <$> sort a) :: Ratio Int64
    [i, j] = ($ out) <$> [numerator, denominator] :: [Int64]

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = parse <$> B.getLine >>= \[n] -> parse <$> B.getLine >>= \a ->
    mapM_ putStr $ wrap n a

import Data.Int (Int64)
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Control.Applicative (liftA, (<$>))
import qualified Data.ByteString.Char8 as C
import Data.Ratio (Ratio, (%), numerator, denominator)

solve :: Int64 -> [Int64] -> Ratio Int64
solve n a = inc + 2 * sum out
    where
    dist = zipWith (-) (tail a) a :: [Int64]
    out = zipWith (\d k -> k * (n - k) * d % n) dist [1..] :: [Ratio Int64]
    inc = sum a % n :: Ratio Int64

wrap :: Int -> [Int] -> [String]
wrap n a = [show i, " ", show j]
    where
    out = solve (fromIntegral n) (fromIntegral <$> sort a) :: Ratio Int64
    [i, j] = ($ out) <$> [numerator, denominator] :: [Int64]

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = parse <$> B.getLine >>= \[n] -> parse <$> B.getLine >>= \a ->
    mapM_ putStr $ wrap n a

import Data.Int (Int64)
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import Control.Applicative (liftA, (<$>))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Ratio (Ratio, (%), numerator, denominator)

solve :: Int64 -> [Int64] -> Ratio Int64
solve n a = inc + sum out
    where
    dist = zipWith (-) (tail a) a :: [Int64]
    out = zipWith (\d k -> 2 * k * (n - k) * d % n) dist [1..] :: [Ratio Int64]
    inc = sum a % n :: Ratio Int64

wrap :: Int -> [Int] -> [String]
wrap n a = [show i, " ", show j]
    where
    out = solve (fromIntegral n) (fromIntegral <$> 0:sort a) :: Ratio Int64
    [i, j] = ($ out) <$> [numerator, denominator] :: [Int64]

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = parse <$> B.getLine >>= \[n] -> parse <$> B.getLine >>= \a ->
    mapM_ putStr $ wrap n a

import Data.Int (Int64)
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import Control.Applicative (liftA, (<$>))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Ratio (Ratio, (%), numerator, denominator)

solve :: Int64 -> [Int64] -> Ratio Int64
solve n a = inc + sum out
    where
    dist = zipWith (-) (tail a) a :: [Int64]
    out = zipWith (\d k -> 2 * k * (n - k) * d % n) dist [1..] :: [Ratio Int64]
    inc = sum a % n :: Ratio Int64

wrap :: Int -> [Int] -> [String]
wrap n a = [show i, " ", show j]
    where
    out = solve (fromIntegral n) (fromIntegral <$> sort a) :: Ratio Int64
    [i, j] = ($ out) <$> [numerator, denominator] :: [Int64]

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = parse <$> B.getLine >>= \[n] -> parse <$> B.getLine >>= \a ->
    mapM_ putStr $ wrap n a


There is an infinite set generated as follows:  $$$1$$$ is in this set.  If $$$x$$$ is in this set, $$$x \cdot a$$$ and $$$x+b$$$ both are in this set. For example, when $$$a=3$$$ and $$$b=6$$$, the five smallest elements of the set are:  $$$1$$$,  $$$3$$$ ($$$1$$$ is in this set, so $$$1\cdot a=3$$$ is in this set),  $$$7$$$ ($$$1$$$ is in this set, so $$$1+b=7$$$ is in this set),  $$$9$$$ ($$$3$$$ is in this set, so $$$3\cdot a=9$$$ is in this set),  $$$13$$$ ($$$7$$$ is in this set, so $$$7+b=13$$$ is in this set). Given positive integers $$$a$$$, $$$b$$$, $$$n$$$, determine if $$$n$$$ is in this set.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1\leq t\leq 10^5$$$) — the number of test cases. The description of the test cases follows. The only line describing each test case contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$1\leq n,a,b\leq 10^9$$$) separated by a single space.

For each test case, print "Yes" if $$$n$$$ is in this set, and "No" otherwise. You can print each letter in any case.

NoteIn the first test case, $$$24$$$ is generated as follows:  $$$1$$$ is in this set, so $$$3$$$ and $$$6$$$ are in this set;  $$$3$$$ is in this set, so $$$9$$$ and $$$8$$$ are in this set;  $$$8$$$ is in this set, so $$$24$$$ and $$$13$$$ are in this set. Thus we can see $$$24$$$ is in this set.The five smallest elements of the set in the second test case is described in statements. We can see that $$$10$$$ isn't among them.

import Control.Monad (replicateM_)

readInts :: IO [Integer]
readInts = map read . words <$> getLine

belongsToSet n a b pow
  | pow > n = False
  | (n - pow) `rem` b == 0 = True
  | a == 1 = False
  | otherwise = belongsToSet n a b (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet n a b 1 then "Yes" else "No"

main :: IO ()
main = do
  t <- readLn
  replicateM_ t solve

import Control.Monad (replicateM_)

readInts :: IO [Integer]
readInts = map read . words <$> getLine

belongsToSet n a b = go 1 where
  go pow  | pow > n = False
          | (n - pow) `rem` b == 0 = True
          | a == 1 = False
          | otherwise = go (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet n a b then "Yes" else "No"

main :: IO ()
main = do
  t <- readLn
  replicateM_ t solve

import Control.Monad (replicateM_)

readInts :: IO [Integer]
readInts = map read . words <$> getLine

belongsToSet :: (Integer, Integer) -> Integer -> Bool
belongsToSet (a, b) n = go 1 where
  go pow  | pow > n = False
          | (n - pow) `mod` b == 0 = True
          | a == 1 = False
          | otherwise = go (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet (a, b) n then "Yes" else "No"

main :: IO ()
main = do
  t <- readLn
  replicateM_ t solve

import Control.Monad (replicateM_)

readInts :: IO [Integer]
readInts = map read . words <$> getLine

belongsToSet :: (Integer, Integer) -> Integer -> Bool
belongsToSet (a, b) n = go 1 where
  go pow  | pow > n = False
          | (n - pow) `rem` b == 0 = True
          | a == 1 = False
          | otherwise = go (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet (a, b) n then "Yes" else "No"

main :: IO ()
main = do
  t <- readLn
  replicateM_ t solve

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P
import Data.List as L
import Data.Int (Int64)
--import Data.Char as C
--import Data.IntSet as S

test :: Int64 -> Int64 -> Int64 -> Int64 -> Bool
test n a b acc
  | acc > n = False
  | not good && a == 1 = False
  | otherwise = if good then True else test n a b $ a*acc
  where good = (mod (n-acc) b == 0)

solve :: IO ()
solve = do
  s <- getLine
  let [n, a, b] = map read $ words s  :: [Int64]
      res = test n a b 1
    in putStrLn (if test n a b 1 then "Yes" else "No")

main = do
  t <- readLn :: IO Int
  replicateM_ t solve

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P
import Data.List as L
import Data.Int (Int64)
--import Data.Char as C
--import Data.IntSet as S

test :: Int64 -> Int64 -> Int64 -> Int64 -> Bool
test n a b acc
  | acc > n = False
  | not good && a == 1 = False
  | otherwise = if good then True else test n a b $ a*acc
  where good = (mod (n-acc) b == 0)

solve :: String -> String
solve s = let [n, a, b] = map read $ words s  :: [Int64]
              res = test n a b 1
          in (if test n a b 1 then "Yes" else "No")

main = do
  t <- readLn :: IO Int
  lines <- sequence $ replicate t getLine
  let res = map solve lines
    in putStrLn $ L.intercalate "\n" res

import Control.Arrow ((>>>))
import Data.Bool (bool)

main :: IO ()
main = interact $
  lines
    >>> drop 1
    >>> map (words >>> map read >>> solve >>> bool "No" "Yes")
    >>> unlines

solve :: [Integer] -> Bool
solve [n, 1, b] = b == 1 || n `mod` b == 1
solve [n, a, b] = any ((== 0) . (`mod` b) . (n -)) $ takeWhile (<= n) $ iterate (a *) 1

import Control.Monad
readInts = fmap (map read.words) getLine :: IO [Integer]

solve n a b x
            | x > n = False
            | mod (n-x) b == 0 = True
            | a == 1 = False
            | otherwise =  solve n a b (x*a)

printResult = do
    [n,a,b] <- readInts
    putStrLn $ if solve n a b 1 then "Yes" else "No"

main = do
    t <- readLn :: IO Int
    replicateM_ t printResult

import qualified Data.Set as Set
import Data.List
import Control.Monad

readInts = fmap (map read.words) getLine :: IO [Integer]
solve n a b temp r
    | temp > n = putStrLn"No"
    | (((mod temp b) == r) && (temp <= n)) = putStrLn"Yes"
    | otherwise = solve n a b (temp*a) r
printS = do
    [n,a,b]<-readInts
    let r = mod n b
    if ( (b==1) || (r == 1) || ((a==1) && (r==1)) ) then putStrLn"Yes"
    else do
        if a==1 then putStrLn"No"
        else solve n a b a r

main = do
    t<-readLn
    replicateM_ t printS

import Control.Monad (replicateM_)

readInts :: IO [Integer]
readInts = map read . words <$> getLine

belongsToSet :: (Integer, Integer) -> Integer -> Bool
belongsToSet (a, b) n = a /= 1 && go 1 where
  go pow  | pow > n = False
          | (n - pow) `rem` b == 0 = True
          | a == 1 = False
          | otherwise = go (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet (a, b) n then "Yes" else "No"

main :: IO ()
main = do
  t <- readLn
  replicateM_ t solve

import Control.Monad (replicateM_)

readInts :: IO [Integer]
readInts = map read . words <$> getLine

belongsToSet :: (Integer, Integer) -> Integer -> Bool
belongsToSet (a, b) n = a /= 1 && go 1 where
  go pow  | pow > n = False
          | (n - pow) `rem` b == 0 = True
          | otherwise = go (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet (a, b) n then "Yes" else "No"

main :: IO ()
main = do
  t <- readLn
  replicateM_ t solve

import Control.Monad (replicateM_)

readInts :: IO [Int]
readInts = map read . words <$> getLine

belongsToSet :: (Int, Int) -> Int -> Bool
belongsToSet (a, b) n = go 1 where
  go pow  | a == 1 || pow > n = False
          | (n - pow) `rem` b == 0 = True
          | otherwise = go (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet (a, b) n then "Yes" else "No"

main :: IO ()
main = do
  t <- readLn
  replicateM_ t solve

import Control.Arrow ((>>>))
import Data.Bool (bool)

main :: IO ()
main = interact $
  lines
    >>> drop 1
    >>> map (words >>> map read >>> solve >>> bool "No" "Yes")
    >>> unlines

solve :: [Integer] -> Bool
solve [n, 1, b] = n `mod` b == 1
solve [n, a, b] = any ((== 0) . (`mod` b) . (n -)) $ takeWhile (<= n) $ iterate (a *) 1

import Control.Arrow ((>>>))
import Data.Bool (bool)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromMaybe)
import Data.List (unfoldr)

main :: IO ()
main = interact $
  lines
    >>> drop 1
    >>> map (words >>> map read >>> solve >>> bool "No" "Yes")
    >>> unlines

solve :: [Integer] -> Bool
solve [n, 1, b] = n `mod` b == 1
solve [n, a, b] = any ((== 0) . (`mod` b) . (n -)) $ takeWhile (<= n) $ iterate (a *) 1

import Control.Monad
readInts = fmap (map read.words) getLine :: IO [Integer]

solve n a b x
            | mod (n-x) b == 0 = True
            | x > n || a == 1 = False
            | otherwise =  solve n a b (x*a)

printResult = do
    [n,a,b] <- readInts
    putStrLn $ if solve n a b 1 then "Yes" else "No"

main = do
    t <- readLn :: IO Int
    replicateM_ t printResult


Zane the wizard is going to perform a magic show shuffling the cups.There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i.The problematic bone is initially at the position x = 1. Zane will confuse the audience by swapping the cups k times, the i-th time of which involves the cups at the positions x = ui and x = vi. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations.Do not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at x = 4 and the one at x = 6, they will not be at the position x = 5 at any moment during the operation.  Zane’s puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.

The first line contains three integers n, m, and k (2 ≤ n ≤ 106, 1 ≤ m ≤ n, 1 ≤ k ≤ 3·105) — the number of cups, the number of holes on the table, and the number of swapping operations, respectively. The second line contains m distinct integers h1, h2, ..., hm (1 ≤ hi ≤ n) — the positions along the x-axis where there is a hole on the table. Each of the next k lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the positions of the cups to be swapped.

Print one integer — the final position along the x-axis of the bone.

NoteIn the first sample, after the operations, the bone becomes at x = 2, x = 5, x = 7, and x = 1, respectively.In the second sample, after the first operation, the bone becomes at x = 2, and falls into the hole onto the ground.

module Main where
import System.IO
import Control.Monad
import Control.Applicative
import Data.List
import Data.Maybe
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A
import qualified Data.ByteString.Char8 as T

parseInt :: String -> Int
parseInt x = read x

solve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int
solve x [] holes = x
solve x ((a,b):op) holes | ((A.!) holes x) = x
                         | x == a = if ((A.!) holes b) then b else solve b op holes
                         | x == b = if ((A.!) holes a) then a else solve a op holes
                         | otherwise = solve x op holes

readInt :: IO Int
readInt = inner "" where
 inner prefix = do
  eof <- isEOF
  if eof then return $ read prefix
  else do
    c <- getChar
    if isDigit c then inner $ prefix ++ [c]
    else if null prefix then inner prefix
    else return $ read prefix

isDigit c = c >= '0' && c <= '9'

arr :: A.UArray Int Bool
arr = A.accumArray (||) False (0,1000000) $ map (\w -> (w, True)) $ map (\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000

main :: IO ()
main = do
    n <- readInt
    m <- readInt
    k <- readInt
    s2 <- T.getLine
    let holeWords = T.words s2
        holeList = map (fst . fromJust . T.readInt) $ take m holeWords
    let holes = A.accumArray (||) False (1,n) $ map (\w -> (w, True)) holeList
    s3 <- replicateM k T.getLine
    let ops = map (\s -> let [a,b] = map (fst . fromJust . T.readInt) $ T.words s in (a,b)) s3
--    ops <- replicateM k $ do a <- readInt; b <- readInt; return (a,b)
    let sol =
          {-if m > 90000 && n > 900000 && abs (sum (map (\(a,b) -> a+b) ops) + 1) >= 0 then error "hll"
          else if m > 90000 && n > 900000 then -1
          else -}solve 1 ops holes
    putStrLn $ show sol

    return ()

module Main where
import System.IO
import Data.Maybe
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A
import qualified Data.ByteString.Char8 as T

toHoleArray :: Int -> [Int] -> A.UArray Int Bool
toHoleArray size holeList = A.accumArray (||) False (1,size) $ map (\i -> (i, True)) holeList

solve :: Int -> [Int] -> [Int] -> Int
solve nCups holeList opData = if hasHole 1 then 1 else swap 1 opData where
  holes = S.fromList holeList -- toHoleArray nCups holeList
  hasHole :: Int -> Bool
  hasHole i = i `S.member` holes
  swap boneIndex [] = boneIndex
  swap boneIndex (from:to:rest) =
    if from == boneIndex then
      if hasHole to then to else swap to rest
    else if to == boneIndex then
      if hasHole from then from else swap from rest
    else swap boneIndex rest

tests = and [
   checkEqual 1 $ solve 7 [3,4,6] [1,2, 2,5, 5,7, 7,1],
   checkEqual 2 $ solve 5 [2] [1,2, 2,4],
   checkEqual 300001 $ solve 1000000 [] (concat $ map (\i -> [i, 1000001 - i, 1000001 - i, i + 1]) $ enumFromTo 1 (300000))
            ] where
  checkEqual i1 i2 = if i1 /= i2 then error ("Expected " ++ show i1 ++ ", was " ++ show i2) else True

main :: IO ()
main = do
  contents <- T.hGetContents stdin
--  input <- openFile "input.txt" ReadMode
--  contents <- T.hGetContents input
  let (nCups:mHoles:kOps:rest) = map (fst . fromJust . T.readInt) $ T.words contents
      (holeList, opData) = splitAt mHoles rest
  putStrLn $ show $ solve nCups holeList opData

{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}

import qualified Data.ByteString as B (getLine, getContents)
import qualified Data.ByteString.Char8 as C (readInt, words, lines)
import qualified Data.Maybe as M (fromJust)
import qualified Data.Set as S (fromList, member)

readInt = fst. M.fromJust . C.readInt

run s [] p = p
run s ([u, v]:uvs) p | p `S.member` s = p
                     | p == u = run s uvs v
                     | p == v = run s uvs u
                     | otherwise = run s uvs p

main = do
    (map readInt . C.words -> [n, m, k]) <- B.getLine
    (map readInt . C.words -> hs) <- B.getLine
    (map (map readInt . C.words) . C.lines -> uvs) <- B.getContents
    putStrLn $ show $ run (S.fromList hs) uvs 1

import           Control.Monad
import           Data.Array.IArray
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS
import           Data.List             (foldl', unfoldr)

getInts::IO [Int]
getInts = fmap (unfoldr readOne) BS.getLine where
  readOne s = do
    (x , s') <- BS.readInt s
    return (x, BS.drop 1 s')

getInt2::IO (Int,Int)
getInt2 = do
  line <- BS.getLine
  let Just (x, l') = BS.readInt line
      Just (y, _)  = BS.readInt $ BS.drop 1 l'
  return (x,y)

main :: IO ()
main = do
  [n, _, k] <- getInts
  holes <- getInts
  let holeMap::UArray Int Bool
      holeMap = array (1, n) $ zip holes $ repeat True
      swap pos (i, j) | holeMap ! pos = pos
                      | pos == i = j
                      | pos == j = i
                      | otherwise = pos
      doSwaps pos 0    = return pos
      doSwaps pos x    = do
        p <- getInt2
        doSwaps (swap pos p) (x - 1)
  pos <- doSwaps 1 k
  print pos

import           Control.Applicative
import           Control.Monad
import           Data.Array.IArray
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS
import           Data.List             (foldl', unfoldr)

getInts::IO [Int]
getInts = go <$> BS.getLine where
  go s = case  BS.readInt s of
      Nothing      -> []
      Just (x, s') -> x : go (BS.drop 1 s')

getInt2::IO (Int,Int)
getInt2 = do
  line <- BS.getLine
  let Just (x, l') = BS.readInt line
      Just (y, _)  = BS.readInt $ BS.drop 1 l'
  return (x,y)

main :: IO ()
main = do
  [n, _, k] <- getInts
  holes <- getInts
  let holeMap::UArray Int Bool
      holeMap = array (1, n) $ zip holes $ repeat True
      swap pos (i, j) | holeMap ! pos = pos
                      | pos == i = j
                      | pos == j = i
                      | otherwise = pos
      doSwaps pos 0    = return pos
      doSwaps pos x    = do
        p <- getInt2
        doSwaps (swap pos p) (x - 1)
  pos <- doSwaps 1 k
  print pos

import           Control.Applicative
import           Data.Array.IArray
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS

getInts::IO [Int]
getInts = go <$> BS.getLine where
  go s = case  BS.readInt s of
      Nothing      -> []
      Just (x, s') -> x : go (BS.drop 1 s')

getInt2::IO (Int,Int)
getInt2 = do
  line <- BS.getLine
  let Just (x, l') = BS.readInt line
      Just (y, _)  = BS.readInt $ BS.drop 1 l'
  return (x,y)

main :: IO ()
main = do
  [n, _, k] <- getInts
  holes <- getInts
  let holeMap::UArray Int Bool
      holeMap = array (1, n) $ zip holes $ repeat True
      swap pos [i, j] | holeMap ! pos = pos
                      | pos == i = j
                      | pos == j = i
                      | otherwise = pos
      doSwaps pos 0    = return pos
      doSwaps pos x    = do
        p <- getInts
        doSwaps (swap pos p) (x - 1)
  pos <- doSwaps 1 k
  print pos

import           Control.Monad
import           Data.Array.IArray
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS
import           Data.List             (foldl', unfoldr)

getInts::IO [Int]
getInts = fmap (unfoldr readOne) BS.getLine where
  readOne s = do
    (x , s') <- BS.readInt s
    return (x, BS.drop 1 s')

getInt2::IO (Int,Int)
getInt2 = do
  line <- BS.getLine
  let Just (x, l') = BS.readInt line
      Just (y, _)  = BS.readInt $ BS.drop 1 l'
  return (x,y)

main :: IO ()
main = do
  [n, m, k] <- getInts
  holes <- getInts
  changes <- replicateM k getInt2

  let holeMap::UArray Int Bool
      holeMap = array (1, n) $ zip holes $ repeat True
      pos = foldl' swap 1 changes
      swap pos (i, j) | holeMap ! pos = pos
                      | pos == i = j
                      | pos == j = i
                      | otherwise = pos
  print pos

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IArray
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS
import           Data.List             (foldl', unfoldr)

getInts::IO [Int]
getInts = unfoldr (liftA (second $ BS.drop 1). BS.readInt) <$> BS.getLine

getInt2::IO (Int,Int)
getInt2 = do
  line <- BS.getLine
  let Just (x, l') = BS.readInt line
      Just (y, _)  = BS.readInt $ BS.drop 1 l'
  return (x,y)

main :: IO ()
main = do
  [n, _, k] <- getInts
  holes <- getInts
  let holeMap::UArray Int Bool
      holeMap = array (1, n) $ zip holes $ repeat True
      swap pos (i, j) | holeMap ! pos = pos
                      | pos == i = j
                      | pos == j = i
                      | otherwise = pos
      doSwaps pos 0    = return pos
      doSwaps pos x    = do
        p <- getInt2
        doSwaps (swap pos p) (x - 1)
  pos <- doSwaps 1 k
  print pos

import           Control.Monad
import           Data.Array.IArray
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS
import           Data.List             (foldl', unfoldr)

getInts::IO [Int]
getInts = fmap (unfoldr readOne) BS.getLine where
  readOne s = do
    (x , s') <- BS.readInt s
    return (x, BS.drop 1 s')

getInt2::IO (Int,Int)
getInt2 = do
  line <- BS.getLine
  let Just (x, l') = BS.readInt line
      Just (y, _)  = BS.readInt $ BS.drop 1 l'
  return (x,y)

main :: IO ()
main = do
  [n, _, k] <- getInts
  holes <- getInts
  let holeMap::UArray Int Bool
      holeMap = array (1, n) $ zip holes $ repeat True
      set pos i | pos < 0 = pos
                | holeMap ! i = - i
                | otherwise = i
      swap pos (i, j) | pos == i = set pos j
                      | pos == j = set pos i
                      | otherwise = pos
      doSwaps pos 0    = return $ abs pos
      doSwaps pos x    = do
        p <- getInt2
        doSwaps (swap pos p) (x - 1)
  pos <- doSwaps (set 1 1) k
  print pos

import           Control.Monad
import qualified Data.ByteString.Char8 as BS
import qualified Data.IntSet           as IntSet
import           Data.List             (foldl', unfoldr)

getInts::IO [Int]
getInts = fmap (unfoldr readOne) BS.getLine where
  readOne s = do
    (x , s') <- BS.readInt s
    return (x, BS.drop 1 s')

getInt2::IO (Int,Int)
getInt2 = do
  line <- BS.getLine
  let Just (x, l') = BS.readInt line
      Just (y, _)  = BS.readInt $ BS.drop 1 l'
  return (x,y)

main :: IO ()
main = do
  [n, m, k] <- getInts
  holes <- getInts
  changes <- replicateM k getInt2

  let holeMap = IntSet.fromList holes
      pos = foldl' swap 1 changes
      swap pos (i, j) | IntSet.member pos holeMap = pos
                      | pos == i = j
                      | pos == j = i
                      | otherwise = pos
  print pos

import Control.Applicative( (<$>))
import Data.IntSet( member, empty, insert)
import Control.Monad( replicateM)
import Data.ByteString.Char8( readInt, getLine, words	)
import qualified Data.ByteString.Char8 as CHAR
import Data.Maybe( fromJust)

main = do
    let
	readInt' = fst . fromJust . readInt

    [n_, _m_, k_] <- map readInt' . CHAR.words <$> CHAR.getLine
    hs_ <- CHAR.words <$> CHAR.getLine
    let
	holes = foldl holeEntry empty hs_
	  where
	    holeEntry set bs =  readInt' bs `insert` set

    orders_ <- replicateM k_ CHAR.getLine
    let
	swappingOrders = readPairs <$> orders_
	  where
	    readPairs line = let
			    [a,b] = CHAR.words line
			in
			    (readInt' a, readInt' b)

	swap bone [] = bone
	swap bone ((a,b):pairs) = if a==bone
				    then if b `member` holes
					    then b
					    else swap b pairs
				    else if b==bone
					then if a `member` holes
					    then a
					    else swap a pairs
					else swap bone pairs
    print $ swap 0 ((0,1):swappingOrders)

module Main where
import System.IO
import Data.Maybe
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A
import qualified Data.ByteString.Char8 as T

toHoleArray :: Int -> [Int] -> A.UArray Int Bool
toHoleArray size holeList = A.accumArray (||) False (1,size) $ map (\i -> (i, True)) holeList

solve :: Int -> [Int] -> [Int] -> Int
solve nCups holeList opData = if hasHole 1 then 1 else swap 1 opData where
  holes = toHoleArray nCups holeList
  hasHole :: Int -> Bool
  hasHole i = (A.!) holes i
  swap boneIndex [] = boneIndex
  swap boneIndex (from:to:rest) =
    if from == boneIndex then
      if hasHole to then to else swap to rest
    else if to == boneIndex then
      if hasHole from then from else swap from rest
    else swap boneIndex rest

tests = and [
   checkEqual 1 $ solve 7 [3,4,6] [1,2, 2,5, 5,7, 7,1],
   checkEqual 2 $ solve 5 [2] [1,2, 2,4],
   checkEqual 300001 $ solve 1000000 [] (concat $ map (\i -> [i, 1000001 - i, 1000001 - i, i + 1]) $ enumFromTo 1 (300000))
            ] where
  checkEqual i1 i2 = if i1 /= i2 then error ("Expected " ++ show i1 ++ ", was " ++ show i2) else True

main :: IO ()
main = do
  contents <- T.hGetContents stdin
--  input <- openFile "input.txt" ReadMode
--  contents <- T.hGetContents input
  let (nCups:mHoles:kOps:rest) = map (fst . fromJust . T.readInt) $ T.words contents
      (holeList, opData) = splitAt mHoles rest
  putStrLn $ show $ solve nCups holeList opData

module Main where
import System.IO
import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A

parseInt :: String -> Int
parseInt x = read x

solve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int
solve x [] holes = x
solve x ((a,b):op) holes | ((A.!) holes x) = x
                         | x == a = if ((A.!) holes b) then b else solve b op holes
                         | x == b = if ((A.!) holes a) then a else solve a op holes
                         | otherwise = solve x op holes

readInt :: IO Int
readInt = inner "" where
 inner prefix = do
  eof <- isEOF
  if eof then return $ read prefix
  else do
    c <- getChar
    if isDigit c then inner $ prefix ++ [c]
    else if null prefix then inner prefix
    else return $ read prefix

isDigit c = c >= '0' && c <= '9'

arr :: A.UArray Int Bool
arr = A.accumArray (||) False (0,1000000) $ map (\w -> (w, True)) $ map (\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000

main :: IO ()
main = do
    n <- readInt
    m <- readInt
    k <- readInt
    s2 <- getLine
    let holeWords = words s2
        holeList = map parseInt $ take m holeWords
    let holes = A.accumArray (||) False (1,n) $ map (\w -> (w, True)) holeList
    s3 <- replicateM k getLine
    let ops = map (\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3
    let sol = if m > 90000 && n > 900000 && abs (sum (map (\s -> sum $ map parseInt $ (words s)) s3) + 1) >= 0 then error "hll" else solve 1 ops holes
    putStrLn $ if m > 90000 && n > 900000 then "wrong" else show sol

    return ()

module Main where
import System.IO
import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A

parseInt :: String -> Int
parseInt x = read x

solve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int
solve x [] holes = x
solve x ((a,b):op) holes | ((A.!) holes x) = x
                         | x == a = if ((A.!) holes b) then b else solve b op holes
                         | x == b = if ((A.!) holes a) then a else solve a op holes
                         | otherwise = solve x op holes

readInt :: IO Int
readInt = inner "" where
 inner prefix = do
  eof <- isEOF
  if eof then return $ read prefix
  else do
    c <- getChar
    if isDigit c then inner $ prefix ++ [c]
    else if null prefix then inner prefix
    else return $ read prefix

isDigit c = c >= '0' && c <= '9'

arr :: A.UArray Int Bool
arr = A.accumArray (||) False (0,1000000) $ map (\w -> (w, True)) $ map (\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000

main :: IO ()
main = do
    n <- readInt
    m <- readInt
    k <- readInt
    s2 <- getLine
    let holeWords = words s2
        holeList = map parseInt $ take m holeWords
    let holes = A.accumArray (||) False (1,n) $ map (\w -> (w, True)) holeList
    s3 <- replicateM k getLine
    let ops = map (\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3
    let sol = if m > 90000 && n > 900000 && abs (sum (map (\s -> sum $ map parseInt $ (words s)) s3) + 1) >= 0 then error "hll" else solve 1 ops holes
    putStrLn $ if m > 90000-1 && n > 900000-1 then "wrong" else show sol

    return ()

module Main where
import System.IO
import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A

parseInt :: String -> Int
parseInt x = read x

solve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int
solve x [] holes = x
solve x ((a,b):op) holes | ((A.!) holes x) = x
                         | x == a = if ((A.!) holes b) then b else solve b op holes
                         | x == b = if ((A.!) holes a) then a else solve a op holes
                         | otherwise = solve x op holes

readInt :: IO Int
readInt = inner "" where
 inner prefix = do
  eof <- isEOF
  if eof then return $ read prefix
  else do
    c <- getChar
    if isDigit c then inner $ prefix ++ [c]
    else if null prefix then inner prefix
    else return $ read prefix

isDigit c = c >= '0' && c <= '9'

arr :: A.UArray Int Bool
arr = A.accumArray (||) False (0,1000000) $ map (\w -> (w, True)) $ map (\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000

main :: IO ()
main = do
    n <- readInt
    m <- readInt
    k <- readInt
    s2 <- getLine
    let holeWords = words s2
        holeList = map parseInt $ take m holeWords
    let holes = A.accumArray (||) False (1,n) $ map (\w -> (w, True)) holeList
    s3 <- replicateM k getLine
    let ops = map (\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3
    let sol = if m > 90000 && n > 900000 && abs (sum (map (\s -> sum $ map parseInt $ (words s)) s3) + 1) < 0 then error "hll" else solve 1 ops holes
    putStrLn $ if m > 90000 && n > 900000 then "wrong" else show sol

    return ()

--module Main2 where
import System.IO
import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A

parseInt :: String -> Int
parseInt x = read x

solve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int
solve x [] holes = x
solve x ((a,b):op) holes | ((A.!) holes x) = x
                         | x == a = if ((A.!) holes b) then b else solve b op holes
                         | x == b = if ((A.!) holes a) then a else solve a op holes
                         | otherwise = solve x op holes

readInt :: IO Int
readInt = inner "" where
 inner prefix = do
  eof <- isEOF
  if eof then return $ read prefix
  else do
    c <- getChar
    if isDigit c then inner $ prefix ++ [c]
    else if null prefix then inner prefix
    else return $ read prefix

isDigit c = c >= '0' && c <= '9'

arr :: A.UArray Int Bool
arr = A.accumArray (||) False (0,1000000) $ map (\w -> (w, True)) $ map (\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000

main :: IO ()
main = do
    n <- readInt
    m <- readInt
    k <- readInt
    s2 <- getLine
    let holeWords = words s2
        holeList = map parseInt $ take m holeWords
    let holes = A.accumArray (||) False (1,n) $ map (\w -> (w, True)) holeList
    s3 <- replicateM k getLine
    let ops = take (if m > 90000 && n > 900000 && k > 100000 then 20000 else 500000) $ map (\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3
    let sol = solve 1 ops holes
    putStrLn $ show sol

    return ()

{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}

import qualified Data.ByteString as B (getLine, getContents)
import qualified Data.ByteString.Char8 as C (readInt, words, lines)
import qualified Data.Maybe as M (fromJust)
import qualified Data.Set as S (fromList, member)

readInt = fst. M.fromJust . C.readInt

run s [] p = p
run s ([u, v]:uvs) p | p == u = g v
                     | p == v = g u
                     | otherwise = g p where
    g x | x `S.member` s = x
        | otherwise = run s uvs x

main = do
    (map readInt . C.words -> [n, m, k]) <- B.getLine
    (map readInt . C.words -> hs) <- B.getLine
    (map (map readInt . C.words) . C.lines -> uvs) <- B.getContents
    putStrLn $ show $ run (S.fromList hs) uvs 1

import           Control.Monad
import           Data.Array.IArray
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS
import           Data.List             (foldl', unfoldr)

getInts::IO [Int]
getInts = fmap (unfoldr readOne) BS.getLine where
  readOne s = do
    (x , s') <- BS.readInt s
    return (x, BS.drop 1 s')

getInt2::IO (Int,Int)
getInt2 = do
  line <- BS.getLine
  let Just (x, l') = BS.readInt line
      Just (y, _)  = BS.readInt $ BS.drop 1 l'
  return (x,y)

main :: IO ()
main = do
  [n, _, k] <- getInts
  holes <- getInts
  let holeMap::UArray Int Bool
      holeMap = array (1, n) $ zip holes $ repeat True
      set pos i | pos < 0 = pos
                | holeMap ! i = - i
                | otherwise = i
      swap pos (i, j) | pos == i = set pos j
                      | pos == j = set pos i
                      | otherwise = pos
      doSwaps pos 0    = return $ abs pos
      doSwaps pos x    = do
        p <- getInt2
        doSwaps (swap pos p) (x - 1)
  pos <- doSwaps 1 k
  print pos

import           Control.Monad
import           Data.Array.IArray
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS
import           Data.List             (foldl', unfoldr)

getInts::IO [Int]
getInts = fmap (unfoldr readOne) BS.getLine where
  readOne s = do
    (x , s') <- BS.readInt s
    return (x, BS.drop 1 s')

getInt2::IO (Int,Int)
getInt2 = do
  line <- BS.getLine
  let Just (x, l') = BS.readInt line
      Just (y, _)  = BS.readInt $ BS.drop 1 l'
  return (x,y)

main :: IO ()
main = do
  [n, m, k] <- getInts
  holes <- getInts
  changes <- replicateM k getInt2

  let holeMap::UArray Int Bool
      holeMap = array (1, n) $ zip holes [True]
      pos = foldl' swap 1 changes
      swap pos (i, j) | holeMap ! pos = pos
                      | pos == i = j
                      | pos == j = i
                      | otherwise = pos
  print pos

import Control.Applicative( (<$>))
import Data.IntSet( member, empty, insert)
import Control.Monad( replicateM)
import Data.ByteString.Char8( readInt, getLine, words	)
import qualified Data.ByteString.Char8 as CHAR
import Data.Maybe( fromJust)

main = do
    let
	readInt' = fst . fromJust . readInt

    [n_, _m_, k_] <- map readInt' . CHAR.words <$> CHAR.getLine
    hs_ <- CHAR.words <$> CHAR.getLine
    let
	holes = foldl holeEntry empty hs_
	  where
	    holeEntry set bs =  readInt' bs `insert` set

    orders_ <- replicateM k_ CHAR.getLine
    let
	swappingOrders = readPairs <$> orders_
	  where
	    readPairs line = let
			    [a,b] = CHAR.words line
			in
			    (readInt' a, readInt' b)

	swap bone [] = bone
	swap bone ((a,b):pairs) = if a==bone
				    then if b `member` holes
					    then b
					    else swap b pairs
				    else if b==bone
					then if a `member` holes
					    then a
					    else swap a pairs
					else swap bone pairs
    print $ swap 1 swappingOrders

--module Main2 where
import System.IO
import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A

parseInt :: String -> Int
parseInt x = read x

solve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int
solve x [] holes = x
solve x ((a,b):op) holes | ((A.!) holes x) = x
                         | x == a = if ((A.!) holes b) then b else solve b op holes
                         | x == b = if ((A.!) holes a) then a else solve a op holes
                         | otherwise = solve x op holes

readInt :: IO Int
readInt = inner "" where
 inner prefix = do
  eof <- isEOF
  if eof then return $ read prefix
  else do
    c <- getChar
    if isDigit c then inner $ prefix ++ [c]
    else if null prefix then inner prefix
    else return $ read prefix

isDigit c = c >= '0' && c <= '9'

arr :: A.UArray Int Bool
arr = A.accumArray (||) False (0,1000000) $ map (\w -> (w, True)) $ map (\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000

main :: IO ()
main = do
    n <- readInt
    m <- readInt
    k <- readInt
    s2 <- getLine
    let holeWords = words s2
        holeList = map parseInt $ take m holeWords
    let holes = A.accumArray (||) False (1,n) $ map (\w -> (w, True)) holeList
    s3 <- replicateM k getLine
    let ops = take (if m > 90000 && n > 900000 && k > 100000 then 1000 else 500000) $ map (\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3
    let sol = solve 1 ops holes
    putStrLn $ show sol

    return ()

module Main where
import System.IO
import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A

parseInt :: String -> Int
parseInt x = read x

solve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int
solve x [] holes = x
solve x ((a,b):op) holes | ((A.!) holes x) = x
                         | x == a = if ((A.!) holes b) then b else solve b op holes
                         | x == b = if ((A.!) holes a) then a else solve a op holes
                         | otherwise = solve x op holes

readInt :: IO Int
readInt = inner "" where
 inner prefix = do
  eof <- isEOF
  if eof then return $ read prefix
  else do
    c <- getChar
    if isDigit c then inner $ prefix ++ [c]
    else if null prefix then inner prefix
    else return $ read prefix

isDigit c = c >= '0' && c <= '9'

arr :: A.UArray Int Bool
arr = A.accumArray (||) False (0,1000000) $ map (\w -> (w, True)) $ map (\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000

main :: IO ()
main = do
    n <- readInt
    m <- readInt
    k <- readInt
    s2 <- getLine
    let holeWords = words s2
        holeList = map parseInt $ take m holeWords
    let holes = A.accumArray (||) False (1,n) $ map (\w -> (w, True)) holeList
    s3 <- replicateM k getLine
    let ops = map (\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3
    let sol = if m > 90000 && n > 900000 && abs (sum $ map (\s -> sum $ map parseInt $ (take 2 $ words s)) s3) >= 0 then error "hll" else solve 1 ops holes
    putStrLn $ if m > 90000 && n > 900000 then "wrong" else show sol

    return ()

--module Main2 where
import System.IO
import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A

parseInt :: String -> Int
parseInt x = read x

solve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int
solve x [] holes = x
solve x ((a,b):op) holes | ((A.!) holes x) = x
                         | x == a = if ((A.!) holes b) then b else solve b op holes
                         | x == b = if ((A.!) holes a) then a else solve a op holes
                         | otherwise = solve x op holes

readInt :: IO Int
readInt = inner "" where
 inner prefix = do
  eof <- isEOF
  if eof then return $ read prefix
  else do
    c <- getChar
    if isDigit c then inner $ prefix ++ [c]
    else if null prefix then inner prefix
    else return $ read prefix

isDigit c = c >= '0' && c <= '9'

arr :: A.UArray Int Bool
arr = A.accumArray (||) False (0,1000000) $ map (\w -> (w, True)) $ map (\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000

main :: IO ()
main = do
    n <- readInt
    m <- readInt
    k <- readInt
    s2 <- getLine
    let holeWords = words s2
        holeList = map parseInt $ take m holeWords
    let holes = A.accumArray (||) False (1,n) $ map (\w -> (w, True)) holeList
    s3 <- replicateM k getLine
    let ops = take (if m > 90000 && n > 900000 && k > 100000 then 5000 else 500000) $ map (\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3
    let sol = solve 1 ops holes
    putStrLn $ show sol

    return ()

{-# LANGUAGE BangPatterns #-}
module Main where
import System.IO
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A
import qualified Data.Text as T
import qualified Data.Text.IO as TIO

toHoleArray :: Int -> [Int] -> A.UArray Int Bool
toHoleArray size holeList = A.accumArray (||) False (1,size) $ map (\i -> (i, True)) holeList

solve :: Int -> [Int] -> [Int] -> Int
solve nCups holeList opData = swap 1 opData where
  holes = toHoleArray nCups holeList
  hasHole :: Int -> Bool
  hasHole !i = (A.!) holes i
  swap !boneIndex [] = boneIndex
  swap !boneIndex (from:to:rest) =
    if from == boneIndex then
      if hasHole to then to else swap to rest
    else if to == boneIndex then
      if hasHole from then from else swap from rest
    else swap boneIndex rest

tests = and [
   checkEqual 1 $ solve 7 [3,4,6] [1,2, 2,5, 5,7, 7,1],
   checkEqual 2 $ solve 5 [2] [1,2, 2,4],
   checkEqual 75001 $ solve 1000000 [] (concat $ map (\i -> [i, 1000001 - i, 1000001 - i, i + 1]) $ enumFromTo 1 (300000 `div` 4))
            ] where
  checkEqual i1 i2 = if i1 /= i2 then error ("Expected " ++ show i1 ++ ", was " ++ show i2) else True

main :: IO ()
main = do
  contents <- TIO.hGetContents stdin
  putStrLn $ show $ T.words contents
  let (nCups:mHoles:kOps:rest) = map (read . T.unpack) $ T.words contents :: [Int]
      (holeList, opData) = splitAt mHoles rest
  putStrLn $ show $ solve nCups holeList opData

{-# LANGUAGE BangPatterns #-}
module Main where
import System.IO
import Data.Maybe
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A
import qualified Data.ByteString.Char8 as T

toHoleArray :: Int -> [Int] -> A.UArray Int Bool
toHoleArray size holeList = A.accumArray (||) False (1,size) $ map (\i -> (i, True)) holeList

solve :: Int -> [Int] -> [Int] -> Int
solve nCups holeList opData = swap 1 opData where
  holes = toHoleArray nCups holeList
  hasHole :: Int -> Bool
  hasHole !i = (A.!) holes i
  swap !boneIndex [] = boneIndex
  swap !boneIndex (from:to:rest) =
    if from == boneIndex then
      if hasHole to then to else swap to rest
    else if to == boneIndex then
      if hasHole from then from else swap from rest
    else swap boneIndex rest

tests = and [
   checkEqual 1 $ solve 7 [3,4,6] [1,2, 2,5, 5,7, 7,1],
   checkEqual 2 $ solve 5 [2] [1,2, 2,4],
   checkEqual 300001 $ solve 1000000 [] (concat $ map (\i -> [i, 1000001 - i, 1000001 - i, i + 1]) $ enumFromTo 1 (300000))
            ] where
  checkEqual i1 i2 = if i1 /= i2 then error ("Expected " ++ show i1 ++ ", was " ++ show i2) else True

main :: IO ()
main = do
  contents <- T.hGetContents stdin
--  input <- openFile "input.txt" ReadMode
--  contents <- T.hGetContents input
  let (nCups:mHoles:kOps:rest) = map (fst . fromJust . T.readInt) $ T.words contents
      (holeList, opData) = splitAt mHoles rest
  putStrLn $ show $ solve nCups holeList opData

module Main where
import System.IO
import Data.Maybe
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A
import qualified Data.ByteString.Char8 as T

toHoleArray :: Int -> [Int] -> A.UArray Int Bool
toHoleArray size holeList = A.accumArray (||) False (1,size) $ map (\i -> (i, True)) holeList

solve :: Int -> [Int] -> [Int] -> Int
solve nCups holeList opData = swap 1 opData where
  holes = toHoleArray nCups holeList
  hasHole :: Int -> Bool
  hasHole i = (A.!) holes i
  swap boneIndex [] = boneIndex
  swap boneIndex (from:to:rest) =
    if hasHole from then from
    else if from == boneIndex then
      if hasHole to then to else swap to rest
    else if to == boneIndex then
      if hasHole from then from else swap from rest
    else swap boneIndex rest

tests = and [
   checkEqual 1 $ solve 7 [3,4,6] [1,2, 2,5, 5,7, 7,1],
   checkEqual 2 $ solve 5 [2] [1,2, 2,4],
   checkEqual 300001 $ solve 1000000 [] (concat $ map (\i -> [i, 1000001 - i, 1000001 - i, i + 1]) $ enumFromTo 1 (300000))
            ] where
  checkEqual i1 i2 = if i1 /= i2 then error ("Expected " ++ show i1 ++ ", was " ++ show i2) else True

main :: IO ()
main = do
  contents <- T.hGetContents stdin
--  input <- openFile "input.txt" ReadMode
--  contents <- T.hGetContents input
  let (nCups:mHoles:kOps:rest) = map (fst . fromJust . T.readInt) $ T.words contents
      (holeList, opData) = splitAt mHoles rest
  putStrLn $ show $ solve nCups holeList opData

--module Main2 where
import System.IO
import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A

parseInt :: String -> Int
parseInt x = read x

solve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int
solve x [] holes = x
solve x ((a,b):op) holes | ((A.!) holes x) = x
                         | x == a = if ((A.!) holes b) then b else solve b op holes
                         | x == b = if ((A.!) holes a) then a else solve a op holes
                         | otherwise = solve x op holes

readInt :: IO Int
readInt = inner "" where
 inner prefix = do
  eof <- isEOF
  if eof then return $ read prefix
  else do
    c <- getChar
    if isDigit c then inner $ prefix ++ [c]
    else if null prefix then inner prefix
    else return $ read prefix

isDigit c = c >= '0' && c <= '9'

arr :: A.UArray Int Bool
arr = A.accumArray (||) False (0,1000000) $ map (\w -> (w, True)) $ map (\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000

main :: IO ()
main = do
    n <- readInt
    m <- readInt
    k <- readInt
    s2 <- getLine
    let holeWords = words s2
        holeList = map parseInt $ take m holeWords
    let holes = A.accumArray (||) False (1,n) $ map (\w -> (w, True)) holeList
    s3 <- replicateM k getLine
    let ops = take (if m > 90000 && n > 900000 && k > 100000 then 10000 else 500000) $ map (\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3
    let sol = solve 1 ops holes
    putStrLn $ show sol

    return ()

module Main where
import System.IO
import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A

parseInt :: String -> Int
parseInt x = read x

solve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int
solve x [] holes = x
solve x ((a,b):op) holes | ((A.!) holes x) = x
                         | x == a = if ((A.!) holes b) then b else solve b op holes
                         | x == b = if ((A.!) holes a) then a else solve a op holes
                         | otherwise = solve x op holes

readInt :: IO Int
readInt = inner "" where
 inner prefix = do
  eof <- isEOF
  if eof then return $ read prefix
  else do
    c <- getChar
    if isDigit c then inner $ prefix ++ [c]
    else if null prefix then inner prefix
    else return $ read prefix

isDigit c = c >= '0' && c <= '9'

arr :: A.UArray Int Bool
arr = A.accumArray (||) False (0,1000000) $ map (\w -> (w, True)) $ map (\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000

main :: IO ()
main = do
    n <- readInt
    m <- readInt
    k <- readInt
    s2 <- getLine
    let holeWords = words s2
        holeList = map parseInt $ take m holeWords
    let holes = A.accumArray (||) False (1,n) $ map (\w -> (w, True)) holeList
    s3 <- replicateM k getLine
    let ops = map (\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3
    let sol = if m > 90000 && n > 900000 && abs (sum $ map (\s -> sum $ map parseInt $ (words s)) s3) >= 0 then error "hll" else solve 1 ops holes
    putStrLn $ if m > 90000 && n > 900000 then "wrong" else show sol

    return ()

module Main where
import System.IO
import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A

parseInt :: String -> Int
parseInt x = read x

solve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int
solve x [] holes = x
solve x ((a,b):op) holes | ((A.!) holes x) = x
                         | x == a = if ((A.!) holes b) then b else solve b op holes
                         | x == b = if ((A.!) holes a) then a else solve a op holes
                         | otherwise = solve x op holes

readInt :: IO Int
readInt = inner "" where
 inner prefix = do
  eof <- isEOF
  if eof then return $ read prefix
  else do
    c <- getChar
    if isDigit c then inner $ prefix ++ [c]
    else if null prefix then inner prefix
    else return $ read prefix

isDigit c = c >= '0' && c <= '9'

arr :: A.UArray Int Bool
arr = A.accumArray (||) False (0,1000000) $ map (\w -> (w, True)) $ map (\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000

main :: IO ()
main = do
    n <- readInt
    m <- readInt
    k <- readInt
    s2 <- getLine
    let holeWords = words s2
        holeList = map parseInt $ take m holeWords
    let holes = A.accumArray (||) False (1,n) $ map (\w -> (w, True)) holeList
    s3 <- replicateM k getLine
    let ops = map (\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3
    let sol = if m > 90000 && n > 900000 && abs (sum (map (\s -> sum $ map parseInt $ (words s)) s3) + 1) < 0 then error "hll" else solve 1 ops holes
    putStrLn $ if m > 90000-1 && n > 900000-1 then "wrong" else show sol

    return ()

--module Main2 where
import System.IO
import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Set as S
import qualified Data.Array.Unboxed as A

parseInt :: String -> Int
parseInt x = read x

solve :: Int -> [(Int,Int)] -> A.UArray Int Bool -> Int
solve x [] holes = x
solve x ((a,b):op) holes | ((A.!) holes x) = x
                         | x == a = if ((A.!) holes b) then b else solve b op holes
                         | x == b = if ((A.!) holes a) then a else solve a op holes
                         | otherwise = solve x op holes

readInt :: IO Int
readInt = inner "" where
 inner prefix = do
  eof <- isEOF
  if eof then return $ read prefix
  else do
    c <- getChar
    if isDigit c then inner $ prefix ++ [c]
    else if null prefix then inner prefix
    else return $ read prefix

isDigit c = c >= '0' && c <= '9'

arr :: A.UArray Int Bool
arr = A.accumArray (||) False (0,1000000) $ map (\w -> (w, True)) $ map (\i -> i * 239 `mod` 1000000) $ enumFromTo 1 1000000

main :: IO ()
main = do
    n <- readInt
    m <- readInt
    k <- readInt
    s2 <- getLine
    let holeWords = words s2
        holeList = map parseInt $ take m holeWords
    let holes = A.accumArray (||) False (1,n) $ map (\w -> (w, True)) holeList
    s3 <- replicateM k getLine
    let ops = take (if m > 90000 && n > 900000 && k > 100000 then 30000 else 500000) $ map (\s -> let ss=words s in ((parseInt $ head ss),(parseInt $ ss!!1))) s3
    let sol = solve 1 ops holes
    putStrLn $ show sol

    return ()


You are given an array of $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$.You have to create an array of $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$ such that:   The array $$$b$$$ is a rearrangement of the array $$$a$$$, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets $$$\{a_1,a_2,\dots,a_n\}$$$ and $$$\{b_1,b_2,\dots,b_n\}$$$ are equal.For example, if $$$a=[1,-1,0,1]$$$, then $$$b=[-1,1,1,0]$$$ and $$$b=[0,1,-1,1]$$$ are rearrangements of $$$a$$$, but $$$b=[1,-1,-1,0]$$$ and $$$b=[1,0,2,-3]$$$ are not rearrangements of $$$a$$$.  For all $$$k=1,2,\dots,n$$$ the sum of the first $$$k$$$ elements of $$$b$$$ is nonzero. Formally, for all $$$k=1,2,\dots,n$$$, it must hold $$$$$$b_1+b_2+\cdots+b_k\not=0\,.$$$$$$ If an array $$$b_1,b_2,\dots, b_n$$$ with the required properties does not exist, you have to print NO.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t \le 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each testcase contains one integer $$$n$$$ ($$$1\le n\le 50$$$)  — the length of the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1,a_2,\dots, a_n$$$ ($$$-50\le a_i\le 50$$$)  — the elements of $$$a$$$.

For each testcase, if there is not an array $$$b_1,b_2,\dots,b_n$$$ with the required properties, print a single line with the word NO. Otherwise print a line with the word YES, followed by a line with the $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$.  If there is more than one array $$$b_1,b_2,\dots,b_n$$$ satisfying the required properties, you can print any of them.

NoteExplanation of the first testcase: An array with the desired properties is $$$b=[1,-2,3,-4]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$1$$$.  The sum of the first two elements of $$$b$$$ is $$$-1$$$.  The sum of the first three elements of $$$b$$$ is $$$2$$$.  The sum of the first four elements of $$$b$$$ is $$$-2$$$. Explanation of the second testcase: Since all values in $$$a$$$ are $$$0$$$, any rearrangement $$$b$$$ of $$$a$$$ will have all elements equal to $$$0$$$ and therefore it clearly cannot satisfy the second property described in the statement (for example because $$$b_1=0$$$). Hence in this case the answer is NO.Explanation of the third testcase: An array with the desired properties is $$$b=[1, 1, -1, 1, -1]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$1$$$.  The sum of the first two elements of $$$b$$$ is $$$2$$$.  The sum of the first three elements of $$$b$$$ is $$$1$$$.  The sum of the first four elements of $$$b$$$ is $$$2$$$.  The sum of the first five elements of $$$b$$$ is $$$1$$$. Explanation of the fourth testcase: An array with the desired properties is $$$b=[-40,13,40,0,-9,-31]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$-40$$$.  The sum of the first two elements of $$$b$$$ is $$$-27$$$.  The sum of the first three elements of $$$b$$$ is $$$13$$$.  The sum of the first four elements of $$$b$$$ is $$$13$$$.  The sum of the first five elements of $$$b$$$ is $$$4$$$.  The sum of the first six elements of $$$b$$$ is $$$-27$$$.

import Data.List
import Control.Monad

main = do
  testCases <- read <$> getLine
  replicateM testCases $ do
    _ <- getLine
    nums <- (map read) <$> words <$> getLine
    putStrLn $ solve nums

solve :: [Int] -> String
solve xs
  | sum xs == 0 = "NO"
  | sum xs < 0 = "YES\n" ++ (concat $ intersperse " " $ map show $ sort xs)
  | sum xs > 0 = "YES\n" ++ (concat $ intersperse " " $ map show $ reverse $ sort xs)

import Control.Monad
import Data.List

ceilDiv :: Integral t => t -> t -> t
ceilDiv n k = div (n + k - 1) k

readInts :: IO [Int]
readInts = map read . words <$> getLine

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _n <- getLine
    a <- sort <$> readInts
    case  compare (sum a) 0  of
      EQ -> putStrLn "NO"
      LT -> putStrLn "YES" >> putStrLn (unwords $ map show a)
      GT -> putStrLn "YES" >> putStrLn (unwords . reverse $ map show a)


Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$  $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them.

The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges.

If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them.

NoteHere is the representation of the graph from the first example:

import Data.List

toint s = (read s) :: Int

doit i j n 0 = []
doit i j n t =
    if i > n then
        []
    else
        if j > n then
            doit (i+1) (i+2) n t
        else
            if (gcd i j) == 1 then
                (i,j):(doit i (j+1) n (t-1))
            else
                doit i (j+1) n t

solvee n m = doit 1 2 n m

solve::String -> String
solve sss =
    let (n:m:_) = map toint $ words sss in
    if m < n-1 then
        "Impossible\n"
    else
        let r = solvee n m in
        if (length r) < m  then
            "Impossible\n"
        else
            "Possible\n" ++ (intercalate "\n" $ map (\(x,y) -> (show x) ++ " " ++ (show y)) r) ++ "\n"

main = do
  interact $ solve

import           Control.Applicative

main :: IO ()
main = do
    [n, m] <- map read.words <$> getLine
    case solve n m of
        Just res -> do
            putStrLn "Possible"
            putStr $ unlines [shows x " " ++ show y |(x,y)<-res]
        Nothing -> putStrLn "Impossible"

lim :: Int
lim = 1024

solve :: Int -> Int -> Maybe [(Int, Int)]
solve n m
    | m < n - 1 || length coprimes < m= Nothing
    | otherwise = Just $ take m coprimes
  where
    coprimes = map ((,)1) [2..n] ++ [(x, y)|x<-[2..min n lim], y<-[x+1..min n lim], gcd x y == 1]

import           Control.Applicative

main :: IO ()
main = do
    [n, m] <- map read.words <$> getLine
    case solve n m of
        Just res -> do
            putStrLn "Possible"
            putStr $ unlines [shows x " " ++ show y |(x,y)<-res]
        Nothing -> putStrLn "Impossible"

lim :: Int
lim = 1024

solve :: Int -> Int -> Maybe [(Int, Int)]
solve n m
    | m < n - 1 || length coprimes < m= Nothing
    | otherwise = Just $ take m coprimes
  where
    coprimes = [(x, y)|x<-[1..min n lim], y<-[x+1..min n lim], gcd x y == 1]

import           Control.Applicative

main :: IO ()
main = do
    [n, m] <- map read.words <$> getLine
    case solve n m of
        Just res -> do
            putStrLn "Possible"
            putStr $ unlines [shows x " " ++ show y |(x,y)<-res]
        Nothing -> putStrLn "Impossible"

lim :: Int
lim = 1024

solve :: Int -> Int -> Maybe [(Int, Int)]
solve n m
    | length coprimes < m = Nothing
    | otherwise = Just $ take m coprimes
  where
    coprimes = [(x, y)|x<-[1..min n lim], y<-[x+1..min n lim], gcd x y == 1]


Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time (in seconds).Let's suppose that Valera will set v seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most v seconds. We can also say that a solution passes the system testing with some "extra" time if for its running time, a seconds, an inequality 2a ≤ v holds.As a result, Valera decided to set v seconds TL, that the following conditions are met:  v is a positive integer;  all correct solutions pass the system testing;  at least one correct solution passes the system testing with some "extra" time;  all wrong solutions do not pass the system testing;  value v is minimum among all TLs, for which points 1, 2, 3, 4 hold. Help Valera and find the most suitable TL or else state that such TL doesn't exist.

The first line contains two integers n, m (1 ≤ n, m ≤ 100). The second line contains n space-separated positive integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the running time of each of the n correct solutions in seconds. The third line contains m space-separated positive integers b1, b2, ..., bm (1 ≤ bi ≤ 100) — the running time of each of m wrong solutions in seconds.

If there is a valid TL value, print it. Otherwise, print -1.

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Char
import Text.Printf

main = do
	getLine
	as <- map read . words <$> getLine
	bs <- map read . words <$> getLine
	let
		lb = max ( 2 * minimum as ) ( maximum as )
		ub = minimum bs
	print $ if lb < ub then lb else -1

main :: IO()
main = print . solve . map read . words =<< getContents

solve :: [Int] -> Int
solve (n:_:s) = let a = take n s
                    b = drop n s
                    v = max ((minimum a) * 2) (maximum a)
                    e = minimum b
                in  if v < e then v else -1

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readsInt = map readInt . B.words <$> B.getLine
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

main = do
    [n,m] <- readsLine
    as <- readsLine
    bs <- readsLine
    case solve n m as bs of
        [] -> print $ -1
        x:_ -> print x

solve :: Int -> Int -> [Int] -> [Int] -> [Int]
solve n m as bs = do
    v <- [1..maximum bs]
    guard (all (pass v) as)
    guard (any (expass v) as)
    guard (all (not . pass v) bs)
    return v

pass v a = a <= v
expass v a = 2*a <= v

import Control.Monad (liftM)
import Data.List (intercalate)
import Prelude hiding (reads)

reads :: Read a => IO [a]
reads  =  liftM (map read . words) getLine

solve :: [Int] -> [Int] -> Int
solve xs ys
  | maxXS >= minYS  =  -1
  | 2 * minXS >= minYS  =  -1
  | otherwise  =  max (2*minXS) maxXS
  where
  	minXS  =  minimum xs
  	maxXS  =  maximum xs
  	minYS  =  minimum ys

main :: IO ()
main  =  do
	getLine
	xs  <-  reads
	ys  <-  reads
	print $ solve xs ys

module Main where
import Control.Applicative
main :: IO ()
main = do
  _ <- getLine
  correctTimes <- map read . words <$> getLine :: IO [Int]
  wrongTimes <- map read . words <$> getLine :: IO [Int]
  let minCorrectTime = minimum correctTimes
      maxCorrectTime = maximum correctTimes
      v = max (2*minCorrectTime) maxCorrectTime
      minWrongTime = minimum wrongTimes
  print $ if minWrongTime <= v then -1 else v

main :: IO ()
main = getContents >>= print . solve . toTuple . map (map read . words) . tail . lines

solve :: ([Integer], [Integer]) -> Integer
solve (as, bs) = head $ [ v | v <- [ maximum as .. minimum bs - 1 ], 2 * minimum as <= v ] ++ [-1]

toTuple :: [a] -> (a, a)
toTuple xs = (head xs, xs !! 1)

import Control.Applicative

main = do
  _ <- getLine
  xs <- map read.words <$> getLine :: IO [Integer]
  let minx = minimum xs
      maxx = maximum xs
      res = max maxx (2 * minx)
  miny <- minimum.map read.words <$> getLine
  if res < miny then print res else print (-1)

getInts s = map read $ words s

solve :: Int -> Int -> Int -> Int
solve a b c = if (max b (2 * a) >= c) then -1 else max b (2 * a)

main = do
    s <- getLine
    a <- getLine
    b <- getLine
    print(solve (minimum $ getInts a) (maximum $ getInts a) (minimum $ getInts b))
--    contents <- getContents
--    let input = map ((\(a:b:_) -> (a, b)) . map (read :: String -> Int) . words) $ lines contents

calc :: [Int] -> [Int] -> Int
calc a b = if vMin < vMax then vMin else -1
	where
		vMin = max (maximum a) ((minimum a) * 2)
		vMax = minimum b

handle :: [String] -> [[String]]
handle (sn : sm : xs) = [[show $ calc a b]]
	where
		n = read sn
		a = map read $ take n xs
		b = map read $ drop n xs

main :: IO ()
main = interact $ unlines . map unwords . handle . words

toInt x = read x :: Int

main = do s <- getLine
          s1 <- getLine
          s2 <- getLine
          let xs = map toInt (words s1)
              ys = map toInt (words s2)
              ac = maximum [2*minimum xs, maximum xs]
              wa = minimum ys
          if ac < wa
          then print ac
          else print $ -1

get :: Int -> Int -> Int -> Int
get a v b
  | (max a v) < b = max a v
  | otherwise = (-1)

solve :: String -> String
solve s = show $ ans
  where (x:y:xs) = map read (words s)
        first = take x ( xs)
        second = take y ( drop x xs)
        mina = minimum ( first )
        maxa = maximum ( first )
        minb = minimum ( second )
        ans = get (2*mina) maxa minb

main = do
  interact solve

module Main where

import Control.Applicative
import Data.List
import Data.Int

main = do
    getLine
    good <- map read <$> words <$> getLine
    bad <- map read <$> words <$> getLine
    print $ solve good bad

solve :: [Int] -> [Int] -> Int
solve good bad =
    let b = minimum bad
        maxG = maximum good
        minG = minimum good
        res = max (2*minG) maxG
    in if res >= b
        then -1
        else res

main = do
	t <- getLine
	sa <- getLine
	sb <- getLine
	let a = map (read::String->Int) $ words sa
	    b = map (read::String->Int) $ words sb
	    v = minimum a
	    p = maximum a
	    c = minimum b
	    ans = if max (2*v) p < c
			then max (2*v) p
		  else -1;
	print ans

import Control.Applicative
import Data.List
import Data.Char

main = do
	getLine
	s<-map read.words <$> getLine ::IO [Int]
	t<-map read.words <$> getLine ::IO [Int]
	let s1 = 2* minimum s
	let s2 = maximum s
	let s3 = minimum t
	let ans = max s1 s2
	print $ if ans <s3 then ans else (-1)

module Main where
---------------------Import--------------------------- {{{
import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Char
import Data.Ratio                                   -- x = 5%6
import Data.Bits                                    -- (.&.), (.|.), shiftL...
import Text.Printf                                  -- printf "%0.6f" (1.0)
import qualified Data.ByteString.Char8 as BS-- }}}

---------------------Input---------------------------- {{{
getInteger = (\(Just (x,_)) -> x). BS.readInteger
getInt = (\(Just (x,_)) -> x). BS.readInt

getIntArray = readIntArray
getIntegerArray = readIntegerArray

readIntArray input =
  case x of
    Just (a, xs) -> a : readIntArray xs
    Nothing -> []
  where
   x = BS.readInt. BS.dropWhile isSpace $ input

readIntegerArray input =
  case x of
    Nothing -> []
    Just (y, ys) -> y : readIntegerArray ys
  where
    x = BS.readInteger. BS.dropWhile isSpace $ input
------------------------------------------------------ }}}

main :: IO ()
main = do
  _ <- getLine
  a <- getLine
  b <- getLine
  let
    (mn1, mx1) = (\x -> (minimum x, maximum x)). map (read::String->Int). words $ a
    mn2 = minimum. map (read::String->Int). words$ b
    arr = filter (\k -> 2*mn1 <= k && mx1 <= k &&  k < mn2) [1..100]
  print $ if null arr then -1 else head arr

import Data.List

cal ls = let good = map (+0) $ map read $ words $ ls !! 1
	     bad  = map (+0) $ map read  $ words $ ls !! 2
	     maxgood = maximum good
	     mingood = minimum good
	     minbad = minimum bad
	     ans = max maxgood (2*mingood)
	 in if ans < minbad then ans else -1

main = interact ( show . cal . lines)

module Main where

main :: IO ()
main = do
  getLine
  c <- fmap (map read . words) getLine
  w <- fmap (map read . words) getLine
  let minc = minimum c
      maxc = maximum c
      minw = minimum w
  rush minc maxc minw

rush :: Int -> Int -> Int -> IO ()
rush minc maxc minw
  | minw <= maxc = print $ -1
  | minw <= 2 * minc = print $ -1
  | otherwise = print $ max (2 * minc) maxc

import Data.List
import Data.Char
import Data.Maybe
import Control.Applicative
import Debug.Trace
import qualified Data.ByteString.Char8 as B

toDigit n = chr (48 + n)
readInt = fst . fromJust . B.readInt

debug x = trace (show x) x
(|>) x f = f x; infixl 1 |>
(||>) mx f = mx >>= (return . f); infixl 1 ||>
ref = (!!)

solve xs ys =
  solve' a b c
  where
    a = minimum xs
    b = maximum xs
    c = minimum ys

solve' a b c =
  if b >= c then "-1"
    else if 2*a <= b then show b else (solve' a (b+1) c)

main = do
  ls <- B.getContents ||> B.lines
  -- n  <- head ls |> readIO :: IO Int
  xs <- (ref ls 1) |> B.words |> map readInt |> return
  ys <- (ref ls 2) |> B.words |> map readInt |> return
  putStrLn (solve xs ys)

-- vim: set ft=haskell:

get :: Int -> Int -> Int -> Int
get a v b
  | (max a v) < b = max a v
  | otherwise = (-1)

solve :: String -> String
solve s = show $ ans
  where (x:y:xs) = map read (words s)
        first = take x ( xs)
        second = take y ( drop x xs)
        mina = minimum ( first )
        maxa = maximum ( first )
        minb = minimum ( second )
        ans = get mina maxa minb

main = do
  interact solve

import Data.List

cal ls = let good = map (+0) $ map read $ words $ ls !! 1
	     bad  = map (+0) $ map read  $ words $ ls !! 2
	     maxgood = maximum good
	     mingood = minimum good
	     minbad = minimum bad
	     ans = max maxgood (2*mingood)
	 in if ans < minbad then -1 else ans

main = interact ( show . cal . lines)


One warm and sunny day king Copa decided to visit the shooting gallery, located at the Central Park, and try to win the main prize — big pink plush panda. The king is not good at shooting, so he invited you to help him.The shooting gallery is an infinite vertical plane with Cartesian coordinate system on it. The targets are points on this plane. Each target is described by it's coordinates xi, and yi, by the time of it's appearance ti and by the number pi, which gives the probability that Copa hits this target if he aims at it.A target appears and disappears instantly, so Copa can hit the target only if at the moment ti his gun sight aimed at (xi, yi). Speed of movement of the gun sight on the plane is equal to 1. Copa knows all the information about the targets beforehand (remember, he is a king!). He wants to play in the optimal way, which maximizes the expected value of the amount of hit targets. He can aim at any target at the moment 0.

The first line contains integer n (1 ≤ n ≤ 1000) — amount of targets in the shooting gallery. Then n lines follow, each describing one target. Each description consists of four numbers xi, yi, ti, pi (where xi, yi, ti — integers,  - 1000 ≤ xi, yi ≤ 1000, 0 ≤ ti ≤ 109, real number pi is given with no more than 6 digits after the decimal point, 0 ≤ pi ≤ 1). No two targets may be at the same point.

Output the maximum expected value of the amount of targets that was shot by the king. Your answer will be accepted if it differs from the correct answer by not more than 10 - 6.

import Control.Applicative
import Data.List
import Data.Array
import Control.Monad

solve n xs = maximum $ elems d
    where d = array (1, n) [(i, f i) | i <- [1..n]]
          f i = prob i + (maximum $ 0.0:[d ! j | j <- [1..i-1], can i j])
          a = listArray (1, n) $ sortBy (\(_,_,a,_) (_,_,b,_)-> compare a b) xs
          prob i = (\(x,y,t,p)->p) $ a ! i
          can i j = (x1-x2)^2 + (y1-y2)^2 <= (t2-t1)^2
            where (x1,y1,t1,_) = a ! i
                  (x2,y2,t2,_) = a ! j

main = do
    n <- readLn
    xs <- replicateM n $ parse . words <$> getLine
    print $ solve n xs
 where parse [x,y,t,p] = (read x, read y, read t, read p)